我想使用GSON将其反序列化为Post列表,但无法弄清楚如何告诉GSON如何忽略根元素“posts”(作为其对象)并只处理数组。 / p>
我有:
Type postTypeList = new TypeToken<List<Post>>(){}.getType();
JsonParser jsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(myJSONString);
JsonObject postsRootObj = jsonElement.getAsJsonObject();
List<Post> postList = gson.fromJson(postsRootObj.get("posts"), postTypeList);
但是我宁愿不拥有整个JsonParser,我宁愿直接将它传递给gson.fromJson函数..有没有办法做到这一点?
{ "posts":
[
{
"username": "John",
"message": "I'm back",
"time": "2010-5-6 7:00:34"
"validator":[{
"prog": "Name1",
"name": "Name2",
"computername": "Name3",
"date": "2010-11-20 19:39:55"
}]
}
,
{
"username": "Smith",
"message": "I've been waiting",
"time": "2010-4-6 10:30:26"
"validator":[{
"prog": "Name1",
"name": "Name2",
"computername": "Name3",
"date": "2010-11-20 19:39:55"
}]
}
]}
答案 0 :(得分:1)
创建一个包含类,其中List<Post>
为其成员
public class PostList{
private List<Post> posts;
// getter and setters for posts
}
然后以类似的方式使用fromJson
List<Post> postList = gson.fromJson(myJSONString,PostList.class);
答案 1 :(得分:0)
上面有一个修正。用法应该是:
PostList postList = gson.fromJson(myJSONString,PostList.class);
Post post = postlist.get(index) //index is the index of list you want to access