pawegio
pawegio

Reputation: 1732

Deserializing json using gson

I have a problem with deserializing following json:

{
   "17":"asdf",
   "18":"fdsa",
   "19":"gfds",
   "34":"vcxz",
   "35":"oiue",
   "36":"oiuy"
}

to:

public class CategoryList {

    List<Category> list;
}

public class Category {

    String id;
    String name;
}

I receive following IllegalStateException:

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

Please tell me where I make mistake.

Upvotes: 1

Views: 181

Answers (2)

promanski
promanski

Reputation: 567

The following json

{
   "17":"asdf",
   "18":"fdsa",
   ...
}

is a JSON object not an array. Your classes (Category and CategoryList) should consume a following json:

{
    list: [
        {id: 17, name: "asdf"},
        {id: 18, name: "fdsa"},
        ....
    ]
}

Change your json or classes.

EDIT: The problem is that (if I understand your sample) your json object has a variable number of fields. This means you have to use something like hashmap instead of your classes. Try to deserialize your json to

Map<int, String>

You can find some help in this answer: https://stackoverflow.com/a/8103092/2880555 (you will be redirected to this link http://programmerbruce.blogspot.com/2011/06/gson-v-jackson.html and asked for search "Gson Code to turn any JSON object into a Map" in that page).

Upvotes: 1

darrengorman
darrengorman

Reputation: 13116

The error is fairly self-explanatory, the deserialiser expects a JSON array, because your class contains a List.

Try the following JSON:

{
    "list": [
        {
            "id": "17",
            "name": "asdf"
        }
    ]
}

which should serialise correctly

Upvotes: 1

Related Questions