Search code examples
javajsonjacksongsonjsonpath

Address elements using json path in Jackson and Gson


I want to address elements in a json object using their json path. Json-path java library provide such facility [1].

 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);

Is it possible to do this using jackson or gson also instead of using json-path ?

Thanks


Solution

  • You can try at method of Jackson JsonNode, which uses JSON pointer expression:

    Eg:

    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\"}}]}";
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node = mapper.readTree(jsonString);
    int pincode = node.at("/delivery_codes/0/postal_code/pin").asInt();