javajsonjacksonobjectmapperjsonnode

how to get the nested item of the json object using Java


I have the following json file test.json

{
  "type" : "object",
  "id" : "123",
  "title" : "Test",
  "properties" : {
    "_picnic" : {
      "type" : "boolean"
....

I am able to get the first level value of the key using the following code. E.g. for type I get object

public static void main(String[] args){

        String exampleRequest = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            exampleRequest = FileUtils.readFileToString(new File("src/main/resources/test.json"), StandardCharsets.UTF_8);
            JsonNode jsonNode = objectMapper.readTree(exampleRequest);

            String type = jsonNode.get("type").asText();
            System.out.println(type);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // System.out.println(exampleRequest);


    }

However I do not get any response when I try to get the value for the second level. E.g. if I do

String type = jsonNode.get("_picnic").asText();
System.out.println(type);

OR the whole object e.g.

String type = jsonNode.get("properties").asText();
System.out.println(type);

I tried doing properties._picnic or properties[0]_picnic but no luck.


Solution

  • The documentation for that method states (emphasis mine):

    Method that will return a valid String representation of the container value, if the node is a value node (method isValueNode() returns true), otherwise empty String.

    Per the snippet of json text you shared, both "properties" and "_picnic" are objects not values so you are getting an empty string. It seems you'd need to use the get method:

    jsonNode.get("properties").get("_picnic").get("type").asText()