使用GSON解析JSON数组 [英] Using GSON to parse a JSON array
问题描述
我有这样一个JSON文件:
I have a JSON file like this:
[{ "number" : "3",
"title" : "hello_world",
},
{ "number" : "2",
"title" : "hello_world",
}]
在文件时有一个根元素,我会用:
Before when files had a root element i would use:
Wrapper w = gson.ftomJson(JSONSTRING, Wrapper.class);
code,但我不能想怎么code中的包装
类作为根元素是一个数组
code but i cant think how to code the Wrapper
class as the root element is an array
我已经尝试使用:
Wrapper[] wrapper = gson.fromJson(jsonLine, Wrapper[].class);
与
public class Wrapper{
String number;
String title;
}
但还没有任何运气。我还能如何阅读本使用这种方法?
But havent had any luck. How else can i read this using this method?
P.S我有这个使用的工作:
P.S i have got this to work using:
JsonArray entries = (JsonArray) new JsonParser().parse(jsonLine);
String title = ((JsonObject)entries.get(0)).get("title");
但我会preFER知道如何使用这两种方法做到这一点(如果可能)
but i would prefer to know how to do it (if possible) with both methods
推荐答案
问题是用逗号阵列的最后一个元素之后造成的(后每个标题
)。如果你删除它,你的数据更改为
Problem is caused by comma after last element of your array (after each title
). If you remove it and change your data to
[{ "number" : "3",
"title" : "hello_world"
},
{ "number" : "2",
"title" : "hello_world"
}]
包装[]数据= gson.fromJson(jElement,包装[]类);
将正常工作。
Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);
will work fine.
这篇关于使用GSON解析JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!