如何解析JSON数组中的机器人与GSON [英] How to Parse JSON Array in Android with Gson

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

问题描述

我要解析JSON阵列和使用GSON。首先,我可以登录JSON输出,服务器responsing客户清楚。

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',
           ....
     },
      ...
 ]

我试过这种结构解析。一类,它依赖于单一的阵列的ArrayList 所有JSONArray。

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类:

Post class:

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

什么是错,我该怎么解决?

What's wrong, how can I solve?

推荐答案

您可以直接解析JSON阵列,无需配备PostEntity包住后一个更多的时间,也不需要新的JSONObject的()。的toString()或者:

You can parse the JSON array directly, don't need wrap your Post with PostEntity one more time, 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 = (List<Post>) gson.fromJson(jsonOutput, listType);

合,以帮助。

Hop that help.

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

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