通过Java访问JSON最内层的值可以通过以下步骤实现:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.5</version>
</dependency>
{
"name": "John",
"age": 30,
"address": {
"city": "New York",
"country": "USA"
}
}
你可以创建一个对应的Java类:
public class Person {
private String name;
private int age;
private Address address;
// getters and setters
}
public class Address {
private String city;
private String country;
// getters and setters
}
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) {
String json = "{\"name\":\"John\",\"age\":30,\"address\":{\"city\":\"New York\",\"country\":\"USA\"}}";
try {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(json);
// 访问最内层的值
String city = rootNode.get("address").get("city").asText();
String country = rootNode.get("address").get("country").asText();
System.out.println("City: " + city);
System.out.println("Country: " + country);
} catch (Exception e) {
e.printStackTrace();
}
}
}
在上述代码中,我们首先使用ObjectMapper
类将JSON字符串解析为JsonNode
对象。然后,通过get
方法逐层获取JSON中的值,并使用asText
方法将其转换为对应的Java类型。
这样,你就可以通过Java访问JSON最内层的值了。
腾讯云相关产品推荐:
领取专属 10元无门槛券
手把手带您无忧上云