How to reach json values ​​in depth of other levels?

Assuming I have this JSON file:

{ "level1" :{ "type": "x" }, "level2" :{ "level3": { "level3": { "type" : "Y" } } } } 

Using Jackson , how can I get a value of type = Y?

Can also be achieved using gson.jar

I have tried so far:

 ObjectMapper ob = new ObjectMapper(); String jsonContent = "..."; JsonNode root = ob.readTree(jsonContent) root.path("level1"); //return results fine root.path("level2").path("level3"); //not return any results root.path("level2/level3"); //not return any results 
+4
source share
2 answers

Your JSON is invalid because you do not separate the key:value pairs with a comma, as shown in http://json.org p>

enter image description here

So change your JSON to

 { "level1" :{ "type": "x" }, <-- add this comma "level2" :{ "level3": { "level3": { "type" : "Y" } } } } 

and now you can use

 JsonNode root = new ObjectMapper().readTree(jsonContent); root.path("level2") .path("level3") .path("level3"); 

Using Gson, your code may look like

 JsonObject root = new JsonParser().parse(jsonContent).getAsJsonObject(); root.getAsJsonObject("level2") .getAsJsonObject("level3") .getAsJsonObject("level3"); 
+1
source

Besides moving the tree with path , which works, you can also consider using the JSON Path, which is directly supported with the at method. Sort of:

 String type = root.at("/level2/level3/level3/type").asText(); 
+1
source

All Articles