Take the 2-minute tour ×

I have this kind of json:

 "1": {"id": 1, "first": "mymethod", "second" : [true, true, false]} ,
 "4": {"id": 2, "first": "foo", "second" : [true, true, false]},
 "67": {"id": 67, "first": "bar", "second": [true, true, false]},
 "70": {"id": 70, "first": "foobar", "second" : [true, true, false]}

I am trying to parse it using gson (using Android) but I cannot for some reason. I have tried a lot of combinations: HashMaps<Integer, TheClass> ; TheClass[] ; ArrayList<TheClass> ; etc... but I still not be able to do it!

Everything, of course, using an auxiliary class for the type in the case of generic:

public class TheClassList extends whatever<TheClass> {}


gson.fromJson(jsonstr, TheClassList.class);

Any help will be appreciated? Thanks a lot.

PS: Note the "index" of each object. It is an integer ever but it isn't consecutive (1,2,99...).

Thank you so much for your answers.

share|improve this question
Is GSON a requirement? Could code.google.com/p/json-simple be an option? –  Alexis Pigeon Oct 28 '12 at 20:04

2 Answers 2

up vote 1 down vote accepted

Notice how you your JSON is a single object with four fields, since there are curly braces {} at the root rather than square brackets []. So any attempt to parse this as a list or an array will not work.

Assuming TheClass is defined as follows:

public class TheClass {

    private int id;
    private String first;
    private boolean[] second; // List<Boolean> would work as well


Then this can be parsed using the following:

TypeToken<Map<Integer, TheClass>> token = new TypeToken<Map<Integer, TheClass>>() {};
Map<Integer, TheClass> map = new Gson().fromJson(jsonstr, token.getType());
share|improve this answer
Thanks for your answer. Finally I used a MapHash and I am learn something new of howto pass the ".class" using TypeToken. Thanks a lot :-). Sorry, I can't vote your answer already. –  José Cabo Oct 29 '12 at 22:27

Your Answer


