Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonNode returning null when findValue method is invoked?

Tags:

java

json

jackson

Here is an example json

{
    "key1": {
        "key2": {
            "key3": "value3"
        }
    }
 }

I want to get the value of key3, which is "value3" The method findValue of JsonNode class should serve the purpose here.

so I tried the following:

final ObjectMapper jsonMapper = new ObjectMapper();

String jsonRoot = "{\"key1\":\n" + "    {\"key2\":\n" + "            {\"key3\":\"value3\"}\n" + "    }\n" + "}";
JsonNode node = jsonMapper.convertValue(jsonRoot,JsonNode.class);
JsonNode found = node.findValue("key3");
System.out.println(found.asText());
System.out.println(found.isObject());

However, I see "found" is null. I am unable to figure out why this failing. I also tried node.findValue("key2"). I still get null.

Thanks

like image 600
brain storm Avatar asked Oct 26 '25 00:10

brain storm


1 Answers

There is difference in between these 2 methods

  1. JsonNode.get() method returns null
  2. Use JsonNode.path(String).asText() which checks if node is present or not, if not then it returns empty string.
like image 133
MukulChakane Avatar answered Oct 28 '25 16:10

MukulChakane