java 怎么读取复杂的json里的值

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class ComplexJsonReadingWithGson {
    public static void main(String[] args) {
        String json = "{ \"name\":\"John\", \"age\":30, \"cars\":[ \"Ford\", \"BMW\", \"Fiat\" ], " +
                      "\"address\": { \"street\":\"Main Street\", \"city\":\"New York\" }}";

        JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();

        // 读取基本类型的值
        String name = jsonObject.get("name").getAsString();
        int age = jsonObject.get("age").getAsInt();
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);

        // 读取数组
        JsonArray cars = jsonObject.getAsJsonArray("cars");
        for (int i = 0; i < cars.size(); i++) {
            System.out.println("Car: " + cars.get(i).getAsString());
        }

        // 读取嵌套对象中的值
        JsonObject address = jsonObject.getAsJsonObject("address");
        String street = address.get("street").getAsString();
        String city = address.get("city").getAsString();
        System.out.println("Street: " + street);
        System.out.println("City: " + city);
    }
}

你可能感兴趣的:(java,json,开发语言)