gpt4 book ai didi

java - 如何使用 Gson 解析 JSON 数组

转载 作者:IT老高 更新时间:2023-10-28 12:43:32 27 4
gpt4 key购买 nike

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

这是我的 JSON 输出:

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

我尝试了这种结构进行解析。一个类,它依赖于所有 JSONArray 的单个 arrayArrayList

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

怎么了,怎么解决?

最佳答案

您可以直接解析 JSONArray,不需要再用 PostEntity 包装您的 Post 类,也不需要新的 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);

希望对您有所帮助。

关于java - 如何使用 Gson 解析 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8371274/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com