Chronos
Chronos

Reputation: 1962

Retrofit + GSON parse an Array of objects

I receive this jason as a response from a WS:

[
   [
     "test0",
     "test0"
   ],
   [
     "test1",
     "test1"
   ],
   [
     "test2",
     "test2"
   ],
   [
     "test3",
     "test3"
   ],
   [
     "test4",
     "test4"
   ],
   [
     "test5",
     "test5"
   ]
]

Notice that there are no name-value fields the json is an array of strings arrays. I tried several attemps to parse the response. I tried with a pojo with a List of strings but I have the same error always:

retrofit.RetrofitError: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

MyPOJO for retrofit callback is the next one:

public class VotePollResults {

    private List<PartialResult> fields;

    public List<PartialResult> getFields() {
        return fields;
    }

    public void setFields(List<PartialResult> fields) {
        this.fields = fields;
    }

    public class PartialResult {

        private String description;
        private Integer votes;

        public PartialResult(String description, Integer votes) {
            this.description = description;
            this.votes = votes;
        }

        public String getDescription() {
            return description;
        }

        public Integer getVotes() {
            return votes;
        }

    }

}

I have a List with a custom object, the one that handle that json structure.

Upvotes: 1

Views: 2033

Answers (2)

Chronos
Chronos

Reputation: 1962

Well I resolved the issue.

I have to use this as callback on retrofit

Callback<List<List<String>>>

Hope this helps to someone...

Upvotes: 2

andrew
andrew

Reputation: 6563

It looks like you are trying to parse Object instead of Array. In case of you response this code will work:

String[][] items = gson.fromJson(s, String[][].class);

Upvotes: 0

Related Questions