GSON帮助的解析阵列 - 作品,未经数组,但不会有数组 [英] Gson help with parse array - works without array but won't with array
本文介绍了GSON帮助的解析阵列 - 作品,未经数组,但不会有数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以帮我GSON解析器。当我从JSON删除变化,结果它工作正常,但改变它抛出JsonParseException-解析失败。
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);
我上课像这样
public class Result {
public String start_time;
public String end_time;
public change[] change;
}
和
public class change {
public String id;
public String name;
}
和JSON字符串如
[
{
"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 ?
推荐答案
正如有人建议,你需要使用一个列表,而不是。 GSON有pretty良好的文档使用parametized类型的解析器,你可以阅读更多关于它的here 。您code最终会看起来像这样:
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);
}
这篇关于GSON帮助的解析阵列 - 作品,未经数组,但不会有数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文