java - 使用 Java 使用 GSON 反序列化 JSON 响应

标签 java json gson

我正在尝试使用 GSON 解析以下 JSON 响应:

{
  "total": 15,
  "page": 2,
  "pagesize": 10,
  "rep_changes": [
    {
      "user_id": 2341,
      "post_id": 2952530,
      "post_type": "question",
      "title": "unprotected access to member in property get",
      "positive_rep": 5,
      "negative_rep": 0,
      "on_date": 1275419872
    },
   {
      "user_id": 2341,
      "post_id": 562948,
      "post_type": "question",
      "title": "Do you have any recommendations on Blend/XAML books/tutorials for designers?",
      "positive_rep": 20,
      "negative_rep": 0,
      "on_date": 1270760339
    }
  ....
}

这是我定义的两个类(每个类都包含各自的 getter 和 setter):

public class Reputation {
    private int total;
    private int page;
    private int pagesize;
    private List<RepChanges> rep_changes;

public class RepChanges {
    private int user_id;
    private int post_id;
    private String post_type;
    private String title;
    private int positive_rep;
    private int negative_rep;
    private long on_date;

我无法将 RepChanges 类解析为 Reputation 类中的 rep_changes 属性。有什么想法吗?

注意:我已经设法解析了总计、页面和页面大小(这些是非复杂属性)。这就是我所做的:

为了解析总计、页面和页面大小,我使用了(并且工作正常):

Gson gson = new Gson();
Reputation rep = gson.fromJson(jsonText, Reputation.class);

//doing this works:
int page = rep.getPage();
System.out.println(page);

但是,在做的时候:

List<RepChanges> rep_changes = rep.getRep_changes();
for(RepChanges r : rep_changes){
    System.out.println(r.toString());
}

我(技术上)没有收到错误,但以下内容(似乎是内存位置):

stackoverflow.objects.RepChanges@116bb691

最佳答案

在您的 Repchanges 类中,配置您自己的 toString() 方法,类似于:

public String toString ()
{
    return "RepChanges [user_id=" + user_id + 
            ", post_id=" + post_id + 
            ", post_type=" + post_type + 
            ", title=" + title + 
            ", positive_rep=" + positive_rep + 
            ", negative_rep=" + negative_rep + 
            ", on_date=" + on_date + "]";
}

关于java - 使用 Java 使用 GSON 反序列化 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9657053/

相关文章:

java - 如何在 Windows 上向 doclet 添加多个源路径?

java - :label tag in Spring?形式有什么好处

java - 将 List<String> 转换为 String 返回类型

java - 如何在绑定(bind)到 JSON 的对象中定义列表?

Python 将 JSON 转换为 CSV

java - JSON 将单个字符串解析为对象

java - JPA中的Id继承

javascript - 如何循环 JSON

android - 使用 Retrofit 将动态 JSON 解析为 POJO

android - 获取 JSONArray 时 Retrofit2 + Gson IllegalStateException