使用Java将GSSON的JSON响应反序列化

时间:2012-03-11 17:16:11

标签: 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属性。有什么想法吗?

注意:我已设法解析total,page和pagesize(这些是非复杂属性)。这就是我所做的:

要解析总数,页数和页面大小,我使用(并且工作正常):

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

1 个答案:

答案 0 :(得分:3)

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 + "]";
}