簡體   English   中英

JAVA Jackson解析包含列表/數組的JSON響應

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

我正在嘗試反序列化JSON字符串,但是我一直遇到JSON Mapping Exception。 我一直在搜尋互聯網,但是運氣不好。

我要反序列化的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
}

這是我得到的錯誤的摘要版:

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)
    ...

我嘗試按照這篇文章中的說明包裝響應,但是仍然遇到相同的錯誤。 從調用stack-trace看來,它似乎與List <Comment>有關 即,我需要傳遞一個列表對象。 這個objectMapper.readValue(json,CommentResponse.class)還不夠嗎?

我的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
}

如果有幫助,我使用的是Jackson版本2.5.3; 目標平台是Android。

編輯:下面的火花解決方案是正確的。 我有一個拼寫錯誤,試圖從錯誤的Web服務解析JSON。

您的JSON格式錯誤。 從錯誤消息中可以看到:

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

似乎解析器遇到的是數組而不是對象。

您的代碼接縫正確。 這是我運行和運行的代碼:

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
}

爪哇

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