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

2023-12-13 16:21:14
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);
    }
}

文章来源:https://blog.csdn.net/minihuabei/article/details/134972214
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。