如何使用GSON反序列化数组的数组

huangapple go评论70阅读模式
英文:

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,&quot;A&quot;],[2,&quot;B&quot;]]

I'm trying to deserialize it with:

public class A {
    @SerializedName(&quot;id&quot;)
    private int id;

    @SerializedName(&quot;name&quot;)
    private String name;
  }

String jstring = &quot;[[1,\&quot;a\&quot;], [2, \&quot;b\&quot;]]&quot;;

Type collectionType = new TypeToken&lt;Collection&lt;A&gt;&gt;() {}.getType();
Gson gson = new Gson();
Collection&lt;A&gt; 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

{&quot;id&quot;:1, &quot;name&quot;:&quot;b&quot;} instead of [1,&quot;b&quot;]

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&lt;List&lt;List&lt;Object&gt;&gt;&gt;() {}.getType();
List&lt;List&lt;Object&gt;&gt; enums = ...

Gson will not map an array to a POJO. For what you want, the JSON should have been:

[{&quot;id&quot;:1, &quot;name&quot;:&quot;a&quot;}, {&quot;id&quot;:2, &quot;name&quot;:&quot;b&quot;}]

As is, converting the List&lt;List&lt;Object&gt;&gt; into a List&lt;A&gt; is up to you.

huangapple
  • 本文由 发表于 2020年9月19日 00:19:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63959364.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定