如何使用 Gson 解析 JSON 数组 [英] How to Parse JSON Array with Gson

查看:37
本文介绍了如何使用 Gson 解析 JSON 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解析 JSON 数组并使用 gson.首先,我可以记录 JSON 输出,服务器清楚地响应客户端.

I want to parse JSON arrays and using gson. Firstly, I can log JSON output, server is responsing to client clearly.

这是我的 JSON 输出:

Here is my JSON output:

 [
      {
           id : '1',
           title: 'sample title',
           ....
      },
      {
           id : '2',
           title: 'sample title',
           ....
     },
      ...
 ]

我尝试了这个结构来解析.一个类,它依赖于所有 JSONArray 的单个 arrayArrayList.

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; 
      } 
 }

帖子类:

 public class Post {

      private String id;
      private String title;

      /* getters & setters */
 }

当我尝试使用 gson 时没有错误,没有警告也没有日志:

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());

怎么了,怎么解决?

推荐答案

你可以直接解析JSONArray,不需要用包裹你的Post类>PostEntity 再一次,也不需要 new JSONObject().toString() :

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);

希望有所帮助.

这篇关于如何使用 Gson 解析 JSON 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆