开发者

Gson help with parse array - works without array but won't with array

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 ?


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜