Programming
Using Jackson and JSON Pointer to query and parse an arbitrary JSON node
JSON Pointer is a string syntax for identifying a specific value within a JSON document, defined by the RFC 6901. Consider the following JSON:
{
"firstName": "John",
"lastName": "Doe",
"address": {
"street": "21 2nd Street",
"city": "New York",
"postalCode": "10021-3100",
"coordinates": {
"latitude": 40.7250387,
"longitude": -73.9932568
}
}
}
The coordinates
node can be identified by following JSON Pointer expression:
/address/coordinates
Jackson 2.3.0 introduced support to JSON Pointer and it can be handy when we want to query a specific node from a JSON document:
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);
JsonNode coordinatesNode = node.at("/address/coordinates");
Then the coordinates
node could be parsed into a bean:
public class Coordinates {
private Double latitude;
private Double longitude;
// Getters and setters omitted
}
Coordinates coordinates = mapper.treeToValue(coordinatesNode, Coordinates.class);