json object from REST service
{
"destination_addresses" : [ "Chicago, IL, USA" ],
"origin_addresses" : [ "Syracuse, NY, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1,090 km",
"value" : 1090383
},
"duration" : {
"text" : "10 hours 21 mins",
"value" : 37242
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
Using code from JacksonInFiveMinutes
ObjectMapper mapper = new ObjectMapper();
Map userData = mapper.readValue(webResource.queryParams(queryParams).get(String.class);, Map.class);
Where:
webResource.queryParams(queryParams).get(String.class);
returns the json from REST service
From Json I would like the 2 address properties as well as the distance property as well as the 2 status.
My hack attempt:
ObjectMapper mapper = new ObjectMapper();
JsonNode jnode = mapper.readValue(s, JsonNode.class);
jnode.findValue("distance").findValue("value") //
this gets me the value I am looking for.
Not sure if this is good way to go about
It looks OK to me, except that it would be safer to not chain those two
findValue()calls together, as you could get a NPE if the JSON string doesn’t contain the first one. From the JsonNode javadoc:So I’d check the first
findValue()result and if its not null, then perform the secondfindValue()(with logging to notify you if this happens).