Java 使用 GSON 解析 JSON 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18421674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using GSON to parse a JSON array
提问by Eduardo
I have a JSON file like this:
我有一个像这样的 JSON 文件:
[
{
"number": "3",
"title": "hello_world",
}, {
"number": "2",
"title": "hello_world",
}
]
Before when files had a root element I would use:
在文件具有根元素之前,我会使用:
Wrapper w = gson.fromJson(JSONSTRING, Wrapper.class);
code but I can't think how to code the Wrapper
class as the root element is an array.
代码,但我想不出如何对Wrapper
类进行编码,因为根元素是一个数组。
I have tried using:
我试过使用:
Wrapper[] wrapper = gson.fromJson(jsonLine, Wrapper[].class);
with:
和:
public class Wrapper{
String number;
String title;
}
But haven't had any luck. How else can I read this using this method?
但一直没有运气。我还能如何使用这种方法阅读这篇文章?
P.S I have got this to work using:
PS我有这个工作使用:
JsonArray entries = (JsonArray) new JsonParser().parse(jsonLine);
String title = ((JsonObject)entries.get(0)).get("title");
But I would prefer to know how to do it (if possible) with both methods.
但我更想知道如何使用这两种方法(如果可能)。
采纳答案by Pshemo
Problem is caused by comma at the end of (in your case each) JSON object placed in the array:
问题是由放置在数组中的 JSON 对象(在您的情况下为每个)末尾的逗号引起的:
{
"number": "...",
"title": ".." , //<- see that comma?
}
If you remove them your data will become
如果您删除它们,您的数据将变成
[
{
"number": "3",
"title": "hello_world"
}, {
"number": "2",
"title": "hello_world"
}
]
and
和
Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);
should work fine.
应该工作正常。
回答by Narendra Pathai
Gson gson = new Gson();
Wrapper[] arr = gson.fromJson(str, Wrapper[].class);
class Wrapper{
int number;
String title;
}
Seems to work fine. But there is an extra ,
Comma in your string.
似乎工作正常。但是,
您的字符串中有一个额外的逗号。
[
{
"number" : "3",
"title" : "hello_world"
},
{
"number" : "2",
"title" : "hello_world"
}
]
回答by chenyueling
public static <T> List<T> toList(String json, Class<T> clazz) {
if (null == json) {
return null;
}
Gson gson = new Gson();
return gson.fromJson(json, new TypeToken<T>(){}.getType());
}
sample call:
示例调用:
List<Specifications> objects = GsonUtils.toList(products, Specifications.class);
回答by shahzeb khan
Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);