1

如何使用 java(对于独立的 java 应用程序)从这个链接解析 json?我尝试了 gson & Jackson 库,但它们似乎有问题,因为这个 json 的格式看起来不同。

你怎么做呢?

鉴于 facebook 的受欢迎程度,我希望找到一些可以做到这一点的 jars/lib。非常欢迎带有示例的建议。非常感谢。

响应.java

public class Response{
private List<Comments> commentslist;

public List<Comments> getCommentsList() {
    return commentslist;
}

public void setCommentsList(List<Comments> commentslist) {
    this.commentslist = commentslist;
}
}

评论.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;
}
}

来自.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;
}
}

数据.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 模型有问题吗?

4

2 回答 2

1

You are trying to deserialize the JSON response(which is an array of objects) into an object(Response) with a list(commentList) of comments(Comments). There is a type/structure mismatch and GSON won't be able to deserialize that.

Try doing something like:

Gson gson = new Gson();
Type collectionType = new TypeToken<List<Response>>(){}.getType();
List<Comments> commentList = gson.fromJson(yourJsonString, collectionType);

And change your Response object into:

public class Response{
  private Comments comments;

  public Comments getComments() {
      return comments;
  }

  public void setComments( Comments comments) {
      this.comments= comments;
  }
}

The json from fb is a list of response(anonymous) objects that has 1 field called comments. Comments, despite the name, is actually an object.

于 2012-08-02T17:42:07.357 回答
0

The JSON validates fine. The top container in that JSON is an array, not an object. Try:

List<Response> responses = gson.fromJson( contents, Response.class );
System.out.println(responses[0].getCommentsList());
于 2012-08-02T17:42:21.787 回答