[英]How to deserialize array of arrays with GSON
I have JSON like this:我有这样的 JSON:
[[1,"A"],[2,"B"]]
I'm trying to deserialize it with:我试图反序列化它:
public class A {
@SerializedName("id")
private int id;
@SerializedName("name")
private String name;
}
String jstring = "[[1,\"a\"], [2, \"b\"]]";
Type collectionType = new TypeToken<Collection<A>>() {}.getType();
Gson gson = new Gson();
Collection<A> enums = gson.fromJson(jstring, collectionType);
}
And getting error并得到错误
Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 3 path $[0]
As i understand gson expect据我了解 gson 期望
{"id":1, "name":"b"} instead of [1,"b"]
So how can I deserialize this JSON?那么如何反序列化这个 JSON 呢?
Since it's an array of array of mixed types, aka a list of list of mixed types, use:由于它是混合类型数组的数组,也就是混合类型列表的列表,请使用:
... = new TypeToken<List<List<Object>>>() {}.getType();
List<List<Object>> enums = ...
Gson will not map an array to a POJO. Gson 不会将数组映射到 POJO。 For what you want, the JSON should have been:
对于你想要的,JSON 应该是:
[{"id":1, "name":"a"}, {"id":2, "name":"b"}]
As is, converting the List<List<Object>>
into a List<A>
is up to you. List<A>
,将List<List<Object>>
转换为List<A>
取决于您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.