要解析复杂的 JSON 数据,可以使用 Fastjson 提供的 JSONPath 表达式来筛选和提取需要的数据。
下面是一个示例,演示如何使用 Fastjson 解析复杂的 JSON 数据:
import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.alibaba.fastjson.JSONArray;public class Main { public static void main(String[] args) { // 复杂的 JSON 数据 String jsonString = "{\"name\":\"John\",\"age\":30,\"address\":{\"street\":\"123 Main St\",\"city\":\"New York\"},\"pets\":[{\"name\":\"Fluffy\",\"type\":\"cat\"},{\"name\":\"Spot\",\"type\":\"dog\"}]}"; // 解析 JSON 数据 JSONObject jsonObject = JSON.parseObject(jsonString); // 获取简单的属性 String name = jsonObject.getString("name"); int age = jsonObject.getIntValue("age"); System.out.println("Name: " + name); System.out.println("Age: " + age); // 获取嵌套的属性 JSONObject address = jsonObject.getJSONObject("address"); String street = address.getString("street"); String city = address.getString("city"); System.out.println("Street: " + street); System.out.println("City: " + city); // 获取数组中的元素 JSONArray pets = jsonObject.getJSONArray("pets"); for (int i = 0; i < pets.size(); i++) { JSONObject pet = pets.getJSONObject(i); String petName = pet.getString("name"); String petType = pet.getString("type"); System.out.println("Pet " + (i + 1) + ": " + petName + " (" + petType + ")"); } }}以上代码会输出以下结果:
Name: JohnAge: 30Street: 123 Main StCity: New YorkPet 1: Fluffy (cat)Pet 2: Spot (dog)这个例子中的 JSON 数据包含了嵌套的对象和数组。使用 Fastjson 的 getXXX 方法可以获取简单的属性,使用 getJSONObject 和 getJSONArray 方法可以获取嵌套的对象和数组中的元素。

