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:
- Parse the JSON string into a JSONObject.
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
JSONObject jsonObject = JSON.parseObject(jsonString);
- 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");
- 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");
- 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.