Java

java怎么解析多层嵌套json

小亿
110
2024-05-21 16:42:25
栏目: 编程语言

在Java中解析多层嵌套的JSON数据可以使用一些流行的JSON解析库,例如Jackson、Gson或者org.json。以下是使用Jackson库解析多层嵌套的JSON数据的示例代码:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonParser {
    
    public static void main(String[] args) {
        String json = "{\"name\": \"John\", \"age\": 30, \"address\": {\"street\": \"123 Main St\", \"city\": \"New York\"}}";
        
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(json);
            
            String name = jsonNode.get("name").asText();
            int age = jsonNode.get("age").asInt();
            JsonNode addressNode = jsonNode.get("address");
            String street = addressNode.get("street").asText();
            String city = addressNode.get("city").asText();
            
            System.out.println("Name: " + name);
            System.out.println("Age: " + age);
            System.out.println("Street: " + street);
            System.out.println("City: " + city);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在上面的示例中,我们使用Jackson库的ObjectMapper类来解析JSON数据,并使用JsonNode对象获取多层嵌套的数据。通过调用get方法并传入相应的键值,我们可以获取到JSON数据中的具体值。

使用其他JSON解析库也类似,只是具体的API可能会有所不同。您可以根据自己的喜好和项目需求选择适合的JSON解析库来解析多层嵌套的JSON数据。

0
看了该问题的人还看了