jamesdeath123
jamesdeath123

Reputation: 4606

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?

Upvotes: 1

Views: 646

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280102

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.

Upvotes: 1

Related Questions