Makar Nikitin
Makar Nikitin

Reputation: 329

How to deserialize array of arrays with GSON

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?

Upvotes: 1

Views: 132

Answers (1)

Andreas
Andreas

Reputation: 159086

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.

Upvotes: 2

Related Questions