How to extract the value of a JSON node using Fastjson?

You can retrieve the value of a JSON node using the fastjson library in the following way:

  1. Parse the JSON string into a JSONObject.
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
JSONObject jsonObject = JSON.parseObject(jsonString);
  1. Retrieve the value of a node using the get method.
String name = jsonObject.getString("name");
int age = jsonObject.getInteger("age");
String city = jsonObject.getString("city");
  1. If the value of the node is a nested JSON object, you can continue to use JSONObject to retrieve it.
String address = jsonObject.getJSONObject("address").getString("street");
  1. If the value of the node is an array, you can retrieve it using JSONArray.
JSONArray jsonArray = jsonObject.getJSONArray("hobbies");
for (int i = 0; i < jsonArray.size(); i++) {
    String hobby = jsonArray.getString(i);
    System.out.println(hobby);
}

Note: In the above code, it is necessary to include the dependency of the fastjson library and use the JSON.parseObject method to parse the json string into a JSONObject object.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds