Assuming that I have this JSON file:
{
"level1" :{
"type": "x"
},
"level2" :{
"level3": {
"level3": {
"type" : "Y"
}
}
}
}
By using Jackson
, how can I get the type = Y value?
It can be also reached by using gson.jar
What I tried so far is:
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
Your JSON is invalid, since you are not separating key:value
pairs with comma ,
as shown in http://json.org
So change your JSON to
{
"level1" :{
"type": "x"
}, <-- add this comma
"level2" :{
"level3": {
"level3": {
"type" : "Y"
}
}
}
}
and now you should be able to use
JsonNode root = new ObjectMapper().readTree(jsonContent);
root.path("level2")
.path("level3")
.path("level3");
Using Gson your code can look like
JsonObject root = new JsonParser().parse(jsonContent).getAsJsonObject();
root.getAsJsonObject("level2")
.getAsJsonObject("level3")
.getAsJsonObject("level3");
Aside from traversing tree with path
, which does work, you may also consider using JSON Path that is directly supported with method at
.
Something like:
String type = root.at("/level2/level3/level3/type").asText();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With