简体   繁体   English

JAVA Jackson解析包含列表/数组的JSON响应

[英]JAVA Jackson Parsing JSON Response that Contains List/Array

I'm trying to deserialize a JSON string but I keep running into JSON Mapping Exception. 我正在尝试反序列化JSON字符串,但是我一直遇到JSON Mapping Exception。 I've been scouring the internet but have had little luck. 我一直在搜寻互联网,但是运气不好。

My JSON response that I'm trying to deserialize looks like the following: 我要反序列化的JSON响应如下所示:

{
   "comments": [{
         "id": "fa6491aeb",
         "user": {
            "userId": "e4dddf5e1",
            "username": "UserX",
            "name": "UserX",
            "profilePhotoUri": ""
         },
         "message": "8: 23 - UserX",
         "timestamp": 1429844781919
      },{
         "id": "ed3e71",
         "user": {
            "userId": "20b8f1",
            "username": "UserW",
            "name": "UserW",
            "profilePhotoUri": ""
         },
         "message": "8: 22 - UserW",
         "timestamp": 1429844780250
      },
      //... more items
   ],
   "canCallerComment": true
}

Here is an abridged version of the error I get: 这是我得到的错误的摘要版:

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.test.android.CommentsResponse out of START_ARRAY token
    at [Source: [{"user":{"userId":"fa6491aeb", ..........]; line: 1, column: 1]
    at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:835)
    at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:831)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromArray(BeanDeserializerBase.java:1220)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:165)
    ...

I tried wrapping my response as mentioned in this post , but I still get the same error. 我尝试按照这篇文章中的说明包装响应,但是仍然遇到相同的错误。 From the call stack-trace, it seems likes it has something to do with List<Comment> . 从调用stack-trace看来,它似乎与List <Comment>有关 Ie, I need to pass a list object. 即,我需要传递一个列表对象。 Is this objectMapper.readValue(json, CommentResponse.class) not sufficient? 这个objectMapper.readValue(json,CommentResponse.class)还不够吗?

My JAVA classes are defined as follows: 我的JAVA类的定义如下:

public class Comment {
    private String id;
    private User user;
    private String message;
    private long timestamp;
    // getter/setters
}

public class CommentResponse {
    List<Comment> comments;
    boolean canCallerComment = false;
    // getter/setters
}

If it helps, I'm using Jackson version 2.5.3; 如果有帮助,我使用的是Jackson版本2.5.3; and the targeted platform is Android. 目标平台是Android。

Edit: Sparks solution below is correct. 编辑:下面的火花解决方案是正确的。 I had a typo where I was trying to parse JSON from the wrong web service. 我有一个拼写错误,试图从错误的Web服务解析JSON。

Your JSON is malformed. 您的JSON格式错误。 As you can see from the error message: 从错误消息中可以看到:

[Source: [{"user":{"userId":"fa6491aeb", ..........]; 

it seems the parser has encountered an array instead of an object. 似乎解析器遇到的是数组而不是对象。

Your code seams correct. 您的代码接缝正确。 Here is the code I ran and worked: 这是我运行和运行的代码:

test.json test.json

{
    "comments": [
    {
        "id": "fa6491aeb",
        "user": {
            "userId": "e4dddf5e1",
            "username": "UserX",
            "name": "UserX",
            "profilePhotoUri": ""
        },
        "message": "8: 23 - UserX",
        "timestamp": 1429844781919
    },
    {
        "id": "ed3e71",
        "user": {
            "userId": "20b8f1",
            "username": "UserW",
            "name": "UserW",
            "profilePhotoUri": ""
        },
        "message": "8: 22 - UserW",
        "timestamp": 1429844780250
    }],
    "canCallerComment": true
}

Java 爪哇

public static void main(String[] args) {

    ObjectMapper objectMapper = new ObjectMapper();

    CommentResponse commentResponse;
    try {
        commentResponse = objectMapper.readValue(
                new File("P:\\projects\\tests\\json-test\\src\\main\\resources\\test.json"),
                CommentResponse.class);
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    commentResponse.getComments();

}

public static class User {
    private String userId;
    private String username;
    private String name;
    private String profilePhotoUri;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getProfilePhotoUri() {
        return profilePhotoUri;
    }

    public void setProfilePhotoUri(String profilePhotoUri) {
        this.profilePhotoUri = profilePhotoUri;
    }
}

public static class Comment {
    private String id;
    private User user;
    private String message;
    private long timestamp;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }
}

public static class CommentResponse {
    List<Comment> comments;
    boolean canCallerComment = false;

    public List<Comment> getComments() {
        return comments;
    }

    public void setComments(List<Comment> comments) {
        this.comments = comments;
    }

    public boolean isCanCallerComment() {
        return canCallerComment;
    }

    public void setCanCallerComment(boolean canCallerComment) {
        this.canCallerComment = canCallerComment;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM