Gson - how to parse dynamic JSON string with nested JSON?

空扰寡人 提交于 2019-12-13 12:12:51

问题


I have JSON string with dynamic elements, till now I parse it into Map:

Map map = new Gson().fromJson(jsonString, 
        new TypeToken<HashMap<String, String>>() {}.getType());

Now I need to solve thsi situation - one of these dynamic variables could be another JSON string.

Do you have some advice ho to solve it? Thanks in advance.

EDIT: JSON string example added (formatted):

{
    "key1": "val1",
    "key2": "val2",
    "key3": {
        "subkey1": [
            "subvalue1",
            "subvalue1"
        ],
        "subkey‌​2": [
            "subvalue2"
        ]
    },
    "key4": "val3"
}

回答1:


What you call another JSON string is just a json object. Change the Map value type to Object from String: TypeToken>

String jsonString = "{\"key1\":\"val1\",\"key2\":\"val2\",\"key3\": {\"subkey1\":\"subvalue1\",\"subkey2\":\"subvalue2\"},\"key4\":\"val3\"}";

Map<String, Object> map = new Gson().fromJson(jsonString, new TypeToken<Map<String, Object>>() {
}.getType());

The above example works with GSON 2.2.2. And sysout(map) produces

{key1=val1, key2=val2, key3={subkey1=subvalue1, subkey2=subvalue2}, key4=val3}

As a small improvement I'd suggest that you explicitly specify map type parameters, and use Map instead of HashMap for the TypeToken.



来源:https://stackoverflow.com/questions/12214781/gson-how-to-parse-dynamic-json-string-with-nested-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!