fastjson怎么解析復(fù)雜json數(shù)據(jù)

小億
146
2023-12-23 21:33:17

要解析復(fù)雜的 JSON 數(shù)據(jù),可以使用 Fastjson 提供的 JSONPath 表達(dá)式來(lái)篩選和提取需要的數(shù)據(jù)。

下面是一個(gè)示例,演示如何使用 Fastjson 解析復(fù)雜的 JSON 數(shù)據(jù):

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;

public class Main {
    public static void main(String[] args) {
        // 復(fù)雜的 JSON 數(shù)據(jù)
        String jsonString = "{\"name\":\"John\",\"age\":30,\"address\":{\"street\":\"123 Main St\",\"city\":\"New York\"},\"pets\":[{\"name\":\"Fluffy\",\"type\":\"cat\"},{\"name\":\"Spot\",\"type\":\"dog\"}]}";

        // 解析 JSON 數(shù)據(jù)
        JSONObject jsonObject = JSON.parseObject(jsonString);

        // 獲取簡(jiǎn)單的屬性
        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);

        // 獲取數(shù)組中的元素
        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 + ")");
        }
    }
}

以上代碼會(huì)輸出以下結(jié)果:

Name: John
Age: 30
Street: 123 Main St
City: New York
Pet 1: Fluffy (cat)
Pet 2: Spot (dog)

這個(gè)例子中的 JSON 數(shù)據(jù)包含了嵌套的對(duì)象和數(shù)組。使用 Fastjson 的 getXXX 方法可以獲取簡(jiǎn)單的屬性,使用 getJSONObjectgetJSONArray 方法可以獲取嵌套的對(duì)象和數(shù)組中的元素。

0