Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How reach json values in depth of other levels?

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
like image 397
The Dr. Avatar asked Jul 28 '15 12:07

The Dr.


2 Answers

Your JSON is invalid, since you are not separating key:value pairs with comma , as shown in http://json.org

enter image description here

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");
like image 152
Pshemo Avatar answered Oct 03 '22 06:10

Pshemo


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();
like image 32
StaxMan Avatar answered Oct 03 '22 06:10

StaxMan