Using GSON to parse a JSON array

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.fromJson(JSONSTRING, Wrapper.class);

code but I can't think how to code the Wrapper class as the root element is an array.

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:

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.

166396 次浏览

Problem is caused by comma at the end of (in your case each) JSON object placed in the array:

{
"number": "...",
"title": ".." ,  //<- see that comma?
}

如果你删除它们,你的数据将成为

[
{
"number": "3",
"title": "hello_world"
}, {
"number": "2",
"title": "hello_world"
}
]

还有

Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);

应该没问题。

Gson gson = new Gson();
Wrapper[] arr = gson.fromJson(str, Wrapper[].class);


class Wrapper{
int number;
String title;
}

似乎工作正常。但有一个额外的 ,逗号在您的字符串。

[
{
"number" : "3",
"title" : "hello_world"
},
{
"number" : "2",
"title" : "hello_world"
}
]
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());
}

样品电话:

List<Specifications> objects = GsonUtils.toList(products, Specifications.class);
Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);