如何使用java解析json from this link(对于独立的java应用程序)?我试过gson&杰克逊图书馆,但他们似乎有问题,因为这个json的格式看起来不同。
你是怎么做到的?
鉴于facebook的受欢迎程度,我希望找到一些可以做到这一点的jar / lib。提供带有示例的建议是最受欢迎的。非常感谢。
Response.java
public class Response{
private List<Comments> commentslist;
public List<Comments> getCommentsList() {
return commentslist;
}
public void setCommentsList(List<Comments> commentslist) {
this.commentslist = commentslist;
}
}
Comments.java
public class Comments{
private Number count;
private List<Data> data;
public Number getCount(){
return this.count;
}
public void setCount(Number count){
this.count = count;
}
public List<Data> getData(){
return this.data;
}
public void setData(List<Data> data){
this.data = data;
}
}
From.java
public class From{
private Number id;
private String name;
public Number getId(){
return this.id;
}
public void setId(Number id){
this.id = id;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
}
Data.java
public class Data{
private Number created_time;
private From from;
private Number id;
private String message;
public Number getCreated_time(){
return this.created_time;
}
public void setCreated_time(Number created_time){
this.created_time = created_time;
}
public From getFrom(){
return this.from;
}
public void setFrom(From from){
this.from = from;
}
public Number getId(){
return this.id;
}
public void setId(Number id){
this.id = id;
}
public String getMessage(){
return this.message;
}
public void setMessage(String message){
this.message = message;
}
}
失败的对话尝试使用gson
Response response = gson.fromJson(contents, Response.class); //contents is json string
System.out.println(response.getCommentsList()); // comes back as null
如果json正常,我的java模型有问题吗?
答案 0 :(得分:1)
您正在尝试将JSON响应(这是一个对象数组)反序列化为一个对象(Response),其中包含注释列表(commentList)(注释)。存在类型/结构不匹配,GSON将无法对其进行反序列化。
尝试做类似的事情:
Gson gson = new Gson();
Type collectionType = new TypeToken<List<Response>>(){}.getType();
List<Comments> commentList = gson.fromJson(yourJsonString, collectionType);
将您的Response对象更改为:
public class Response{
private Comments comments;
public Comments getComments() {
return comments;
}
public void setComments( Comments comments) {
this.comments= comments;
}
}
来自fb的json是一个响应(匿名)对象列表,其中包含一个名为comments的字段。尽管名称,评论实际上是一个对象。
答案 1 :(得分:0)
JSON validates罚款。该JSON中的顶级容器是一个数组,而不是一个对象。尝试:
List<Response> responses = gson.fromJson( contents, Response.class );
System.out.println(responses[0].getCommentsList());