如何用Gson分析JSON数组 [英] How to Parse JSON Array with Gson
问题描述
我想解析JSON数组并使用gson。首先,我可以记录JSON输出,服务器清楚地响应客户端。
以下是我的JSON输出:
$ b <$ c $ [
{
id:'1',
title:'sample title',
....
},
{
id:'2',
title:'sample title',
....
},
...
]
我尝试了这种解析结构。一个类,依赖于单个 array
和 ArrayList
用于所有JSONArray。
public class PostEntity {
private ArrayList< Post> postList = new ArrayList< Post>();
公共列表< Post> getPostList(){
return postList;
public void setPostList(List< Post> postList){
this.postList =(ArrayList< Post> postList;
$ / code $ / pre
$ b $ Post类:
public class Post {
private String id;
私有字符串标题;
/ * getters& setters * /
}
当我尝试使用gson no error时,没有警告,也没有log:
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
PostEntity postEnt;
JSONObject jsonObj = new JSONObject(jsonOutput);
postEnt = gson.fromJson(jsonObj.toString(),PostEntity.class);
Log.d(postLog,postEnt.getPostList()。get(0).getId());
有什么不对,我该如何解决?
JSONArray ,不需要包装你的 Post $ c> $ c> class with PostEntity
多一次,并且不需要新的 JSONObject()。toString()
Gson gson = new Gson();
String jsonOutput =您的JSON字符串;
Type listType = new TypeToken< List< Post>>(){}。getType();
列表< Post> posts = gson.fromJson(jsonOutput,listType);
希望有所帮助。
I want to parse JSON arrays and using gson. Firstly, I can log JSON output, server is responsing to client clearly.
Here is my JSON output:
[
{
id : '1',
title: 'sample title',
....
},
{
id : '2',
title: 'sample title',
....
},
...
]
I tried this structure for parsing. A class, which depends on single array
and ArrayList
for all JSONArray.
public class PostEntity {
private ArrayList<Post> postList = new ArrayList<Post>();
public List<Post> getPostList() {
return postList;
}
public void setPostList(List<Post> postList) {
this.postList = (ArrayList<Post>)postList;
}
}
Post class:
public class Post {
private String id;
private String title;
/* getters & setters */
}
When I try to use gson no error, no warning and no log:
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
PostEntity postEnt;
JSONObject jsonObj = new JSONObject(jsonOutput);
postEnt = gson.fromJson(jsonObj.toString(), PostEntity.class);
Log.d("postLog", postEnt.getPostList().get(0).getId());
What's wrong, how can I solve?
解决方案 You can parse the JSONArray
directly, don't need to wrap your Post
class with PostEntity
one more time and don't need new JSONObject().toString()
either:
Gson gson = new Gson();
String jsonOutput = "Your JSON String";
Type listType = new TypeToken<List<Post>>(){}.getType();
List<Post> posts = gson.fromJson(jsonOutput, listType);
Hope that helps.
这篇关于如何用Gson分析JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文