Basic use of JSONPath in Java

Cannoliopsida picture Cannoliopsida · Jun 25, 2014 · Viewed 93k times · Source

I have JSON as a string and a JSONPath as a string. I'd like to query the JSON with the JSON path, getting the resulting JSON as a string.

I gather that Jayway's json-path is the standard. The online API, however, doesn't have have much relation to the actual library you get from Maven. GrepCode's version roughly matches up though.

It seems like I ought to be able to do:

String originalJson; //these are initialized to actual data
String jsonPath;
String queriedJson = JsonPath.<String>read(originalJson, jsonPath);

The problem is that read returns whatever it feels most appropriate based on what the JSONPath actually finds (e.g. a List<Object>, String, double, etc.), thus my code throws an exception for certain queries. It seems pretty reasonable to assume that there'd be some way to query JSON and get JSON back; any suggestions?

Answer

Ankur Choudhary picture Ankur Choudhary · May 23, 2015

There definitely exists a way to query Json and get Json back using JsonPath. See example below:

 String jsonString = "{\"delivery_codes\": [{\"postal_code\": {\"district\": \"Ghaziabad\", \"pin\": 201001, \"pre_paid\": \"Y\", \"cash\": \"Y\", \"pickup\": \"Y\", \"repl\": \"N\", \"cod\": \"Y\", \"is_oda\": \"N\", \"sort_code\": \"GB\", \"state_code\": \"UP\"}}]}";
 String jsonExp = "$.delivery_codes";
 JsonNode pincodes = JsonPath.read(jsonExp, jsonString, JsonNode.class);
 System.out.println("pincodesJson : "+pincodes);

The output of the above will be inner Json.

[{"postal_code":{"district":"Ghaziabad","pin":201001,"pre_paid":"Y","cash":"Y","pickup":"Y","repl":"N","cod":"Y","is_oda":"N","sort_code":"GB","state_code":"UP"}}]

Now each individual name/value pairs can be parsed by iterating the List (JsonNode) we got above.

for(int i = 0; i< pincodes.size();i++){
    JsonNode node = pincodes.get(i);
    String pin = JsonPath.read("$.postal_code.pin", node, String.class);
    String district = JsonPath.read("$.postal_code.district", node, String.class);
    System.out.println("pin :: " + pin + " district :: " + district );
}

The output will be:

pin :: 201001 district :: Ghaziabad

Depending upon the Json you are trying to parse, you can decide whether to fetch a List or just a single String/Long value.

Hope it helps in solving your problem.