How to parse this JSON with GSON?
gson, java, json
Solution
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)
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]}
Problem
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: ``` { "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: ``` 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!