请考虑以下 JSON:
{
"firstName": "John",
"lastName": "Doe",
"address": {
"street": "21 2nd Street",
"city": "New York",
"postalCode": "10021-3100",
"coordinates": {
"latitude": 40.7250387,
"longitude": -73.9932568
}
}
}
并考虑您要将节点解析为以下 Java 类:coordinates
public class Coordinates {
private Double latitude;
private Double longitude;
// Default constructor, getters and setters omitted
}
为此,请使用 ObjectMapper
将整个 JSON 解析为 JsonNode
:
String json = "{\"firstName\":\"John\",\"lastName\":\"Doe\",\"address\":{\"street\":"
+ "\"21 2nd Street\",\"city\":\"New York\",\"postalCode\":\"10021-3100\","
+ "\"coordinates\":{\"latitude\":40.7250387,\"longitude\":-73.9932568}}}";
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(json);
然后使用 JSON 指针查询节点,并使用 ObjectMapper
将其解析为类:coordinates
Coordinates
JsonNode coordinatesNode = node.at("/address/coordinates");
Coordinates coordinates = mapper.treeToValue(coordinatesNode, Coordinates.class);
JSON 指针是一种遍历 JSON 的路径语言。有关更多详细信息,请查看 RFC 6901。它自2.3版本起在Jackson中可用。