更新时间:2022-10-21 23:31:21
你调用另一个JSON字符串只是一个json对象。从字符串更改Map值类型为 Object :TypeToken>
String jsonString ={\key1 \:\val1 \,\key2 \:\val2 \,\key3 \:{\subkey1 \ :\ subvalue1\ \ subkey2\:\ subvalue2\},\ key4\:\ val3\};
地图< String,Object> map = new Gson()。fromJson(jsonString,new TypeToken< Map< String,Object>>(){
} .getType());
上面的例子适用于GSON 2.2.2。并且sysout(map)产生
$ p $ lt; code> {key1 = val1,key2 = val2,key3 = {subkey1 = subvalue1,subkey2 = subvalue2} ,key4 = val3}
作为一个小改进,我建议您明确指定地图类型参数,并使用Map而不是HashMap作为TypeToken。
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"
],
"subkey2": [
"subvalue2"
]
},
"key4": "val3"
}
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.