英文:
How to deserialize array of arrays with GSON
问题
我有一个类似这样的 JSON:
[[1,"A"],[2,"B"]]
我尝试用以下代码进行反序列化:
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);
}
但是出现了以下错误:
Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 3 path $[0]
根据我理解,Gson 期望的是这样的格式:
{"id":1, "name":"b"} 而不是 [1,"b"]
那么我应该如何反序列化这个 JSON?
英文:
I have JSON like this:
[[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
{"id":1, "name":"b"} instead of [1,"b"]
So how can I deserialize this JSON?
答案1
得分: 2
因为这是一个包含混合类型的数组数组,也就是一个混合类型列表的列表,所以可以使用:
... = new TypeToken<List<List<Object>>>() {}.getType();
List<List<Object>> enums = ...
Gson 不会将数组映射到一个 POJO。对于您想要的情况,JSON 应该是:
[{"id":1, "name":"a"}, {"id":2, "name":"b"}]
目前情况下,将 List<List<Object>>
转换为 List<A>
由您决定。
英文:
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. For what you want, the JSON should have been:
[{"id":1, "name":"a"}, {"id":2, "name":"b"}]
As is, converting the List<List<Object>>
into a List<A>
is up to you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论