如何用GSON解析这个JSON?

时间:2021-09-25 13:41:37

I'am struggling with a problem to parse a JSON with GSON which contains lists as values. This should be pretty simple, but I can't figure out how to solve it. The JSON is:

我正在努力解决使用包含列表作为值的GSON解析JSON的问题。这应该很简单,但我无法弄清楚如何解决它。 JSON是:

{
  "key1": [
    "foo1",
    "foo2",
    "foo3"
  ],
  "key2": [
    "foo4",
    "foo5",
    "foo6"
  ],
  "key3": [
    "foo7",
    "foo8",
    "foo9"
   ]
}

I think the best way is to put it into a Map<String, List<String>>, but I can't create a Type for it. Like:

我认为最好的方法是将它放入Map >,但我不能为它创建一个Type。喜欢: ,list>

Type jsonArrayType = new TypeToken<Map<String, List<String>>>(){}.getType();
// Doesn't work, causes exception: "com.google.gson.internal.LinkedTreeMap cannot be cast to java.util.List"

Thanks for any help!

谢谢你的帮助!

1 个解决方案

#1


5  

You will get a java.lang.reflect.Type from the getType() method. Use that to parse your json. Here is a small working example (Java 7)

您将从getType()方法获取java.lang.reflect.Type。用它来解析你的json。这是一个小工作示例(Java 7)

String json = "{\"key1\": [\"foo1\",\"foo2\",\"foo3\"],\"key2\": [\"foo4\",\"foo5\",\"foo6\"],\"key3\": [\"foo7\",\"foo8\",\"foo9\"]}";
java.lang.reflect.Type type = new TypeToken<Map<String, List<String>>>(){}.getType();
Map<String, List<String>> map = new Gson().fromJson(json, type);
System.out.println(map);

This snippet prints the below value

此代码段打印以下值

{key1=[foo1, foo2, foo3], key2=[foo4, foo5, foo6], key3=[foo7, foo8, foo9]}

{key1 = [foo1,foo2,foo3],key2 = [foo4,foo5,foo6],key3 = [foo7,foo8,foo9]}

#1


5  

You will get a java.lang.reflect.Type from the getType() method. Use that to parse your json. Here is a small working example (Java 7)

您将从getType()方法获取java.lang.reflect.Type。用它来解析你的json。这是一个小工作示例(Java 7)

String json = "{\"key1\": [\"foo1\",\"foo2\",\"foo3\"],\"key2\": [\"foo4\",\"foo5\",\"foo6\"],\"key3\": [\"foo7\",\"foo8\",\"foo9\"]}";
java.lang.reflect.Type type = new TypeToken<Map<String, List<String>>>(){}.getType();
Map<String, List<String>> map = new Gson().fromJson(json, type);
System.out.println(map);

This snippet prints the below value

此代码段打印以下值

{key1=[foo1, foo2, foo3], key2=[foo4, foo5, foo6], key3=[foo7, foo8, foo9]}

{key1 = [foo1,foo2,foo3],key2 = [foo4,foo5,foo6],key3 = [foo7,foo8,foo9]}