简体   繁体   中英

How can I cast json recursively using gson.fromjson

Given I have the following json structure:

{
    "Role": {
        "id": "5",
        "name": "bb1",
        "description": "desc1",
        "PermissionDeck": [
            {
                "id": "7",
                "Permission": [
                    {
                        "id": "398"
                    },
                    {
                        "id": "399"
                    },
                    {
                        "id": "400"
                    },
                    {
                        "id": "401"
                    },
                    {
                        "id": "402"
                    }
                ],
                "Limit": [
                    {
                        "id": "4"
                    },
                    {
                        "id": "5"
                    }
                ]
            }
        ]
    }
}

If I want to cast this into a LinkedTreeMap result so that its content could be a retrieved by:

result.get("Role") returns Map

and

result.get("Role").get("PermissionDeck").size() == 5

and

result.get("Role").get("PermissionDeck").get(0).get("id") == 398

basically makes gson.fromjson recursively go into the structure, and fold any nested structure into LinkedTreeMap until it gets to the most inner layer, which then gets into LinkedTreeMap

Is this possible without writing custom recursive methods?

You can't. The closest you'll get is with JsonObject and using the appropriate getter for each nested member. In other words, your code needs to be explicit about what it expects in the JSON.

For example

JsonObject result = new Gson().fromJson(theJson), JsonObject.class);
System.out.println(result.getAsJsonObject("Role").getAsJsonArray("PermissionDeck").size());

will print 1 since you only have one element in the JSON array named PermissionDeck in the JSON object named Role in the root JSON object.

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