1

Can somebody help me with Gson parser. When I remove change from JSON and Result it works fine but with change it throws JsonParseException-Parse failed.

Result[] response = gson.fromJson(fileData.toString(), Result[].class);

I have classes like this

public class Result {
    public String start_time;
    public String end_time;
    public change[] change;
}

and

public class change {
    public String id;
    public String name;
}

and Json string like

[
  {
        "start_time": "8:00",
        "end_time": "10:00",
        "change": [
            {
                "id": "1",
                "name": "Sam"
            },
            {
                "id": "2",
                "name": "John"
            }
        ]
    },
    {
        "start_time": "9:00",
        "end_time": "15:00",
        "change": [
            {
                "id": "1",
                "name": "Sam"
            },
            {
                "id": "2",
                "name": "John"
            }
        ]
    }
]

Can somebody tell me what I did wrong ? Any idea why it won't work with array ?

Perception
  • 79,279
  • 19
  • 185
  • 195
Damir
  • 54,277
  • 94
  • 246
  • 365

1 Answers1

5

As has been suggested, you need to use a list instead. Gson has pretty good documentation for using parametized types with the parser, you can read more about it here. Your code will end up looking like this:

Type listType = new TypeToken<List<Result>>() {}.getType();
List<Result> results = gson.fromJson(reader, listType);
for (Result r : results) {
    System.out.println(r);
}
Perception
  • 79,279
  • 19
  • 185
  • 195
  • I tried, but it is the same error. It isn't problem in array Result, it works when in json is not embedded array CHANGE. But it won't work when is in Json. That part I don't understand. – Damir Aug 03 '11 at 20:48
  • @Damir - not sure I follow your problem. I constructed a working test case based on what you posted above, you might want to expand your question with some of the code that is *not* working. – Perception Aug 03 '11 at 20:52
  • works perfectly in a very complex jsonArray with multiple arrays and objects inside it. Thank you very much. – Roger Garzon Nieto Mar 07 '13 at 20:15