简体   繁体   中英

How to iterate through N levels of a JSONObject?

I'm wondering does anyone know if it's possible to iterate through N levels of this JSON model, and if so how? I'm doing this in JAVA and I've got access to the Gson library.

{
    "description": "Name of the level",
    "value": "Name of the value",
    "cat": {
        "description":"Name of the level",
        "value": "Name of the value",
        "cat": {
            "description":"Name of the level",
            "value": "Name of the value",
            "cat": {                
                "description":"Name of the level",
                "value": "Name of the value",
                "cat" : {
                    "description":"Name of the level",
                    "value": "Name of the value",
                    "cat": null
                    }
                }           
            }
        }
    }

What I want to do is to be able to go through this JSON and retrieve the "description" and "value" for each level, without knowing how many levels there are. In some cases, there could only be 2 levels, while other times there might be as many as 10.

I've tried this approach in JAVA:

Map<String, Object> map = gson.fromJson(jsonGeneric, new  TypeToken<Map<String, Object>>() {}.getType());
map.forEach((x, y) -> System.out.println("key : " + x + " , value : " + y));

However, that only iterates through the first level and I can't figure out a way to adapt the code to iterate through multiple levels or come up with another solution.

Thanks to Carl Shiles for your comment, it set me on the right track. So the final code which does what i was looking for is the following:

  JsonParser jsonParser = new JsonParser();
    JsonElement jo = jsonParser.parse(jsonGeneric);
    while (!jo.isJsonNull()) {
        System.out.println(jo.getAsJsonObject().get("description").getAsString());
        System.out.println(jo.getAsJsonObject().get("value").getAsString());
        jo = jo.getAsJsonObject().get("cat");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM