我正在尝试使用 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/