小编典典

如何使用Gson解析JSON数组

json

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

这是我的JSON输出:

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

我尝试了这种结构进行解析。一个类,该类取决于单个JSONArray arrayArrayList所有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时,没有错误,没有警告,也没有日志:

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

怎么了,我该怎么解决?


阅读 369

收藏
2020-07-27

共1个答案

小编典典

您可以JSONArray直接解析直接类,不需要再花更多时间包装您的Post类,PostEntity也不需要新的类JSONObject().toString()

Gson gson = new Gson();
String jsonOutput = "Your JSON String";
Type listType = new TypeToken<List<Post>>(){}.getType();
List<Post> posts = gson.fromJson(jsonOutput, listType);

希望有帮助。

2020-07-27