无法使用Jackson解析JSON

时间:2019-01-30 10:05:45

标签: java json jackson jackson-databind mongo-jackson-mapper

我的代码中有一个mongo数据库调用。来自数据库的响应是使用codehaus jackson映射的。

Json:

[
  {
    "_id": "555",
    "rates": 1,
    "reviews": [
      {
        "author_name": "Instructor 9999",
        "_authKey": "demo\\556",
        "text": "asdfa",
        "date": 551,
        "_id": "5454-4920",
        "title": "asdf",
        "comments": []
      }
    ],
    "votedUsers": [
      {
        "mng\\39999": 4
      }
    ],
    "rating": 4
  },
  {
    "_id": "45589",
    "rates": 1,
    "reviews": [
      {
        "author_name": "feef",
        "_authKey": "ad\\ads",
        "text": "Working perfect",
        "date": 1498659163,
        "_id": "asdas-319",
        "title": "test",
        "comments": []
      }
    ],
    "votedUsers": [
      {
        "abc\\bis@cdf.com": 4
      }
    ],
    "rating": 4
  }
]

我创建了以下DTO结构:

@JsonIgnoreProperties(ignoreUnknown = true)
public class MaterialReviewsDTO implements Serializable {

    private static final long serialVersionUID = 1L;
    private String _id;
    private int rates;
    private List<ReviewsDTO> reviews;
    private List<VotedUsersDTO> votedUsers;
    //List<TypeReference<HashMap<String, String>>> votedUsers;
    private int rating;.
    //Getter Setter
}

@JsonIgnoreProperties(ignoreUnknown = true)
public class VotedUsersDTO implements Serializable {

    private static final long serialVersionUID = 1L;
    private Map<String, String> votedUser;
    //Getter Setter
}

以下是我触发查询的代码:

List<MaterialReviewsDTO> materialReviewsDTOs = DBConnectionRealmByDBName
                    .find(query,
                            MaterialReviewsDTO.class,
                            CollectionNameConstant.REVIEWS_COLLECTION);

问题在于,除以下部分外,所有JSON都已在DTO中映射:

"votedUsers" : [ 
            {
                "abc\\bis@cdf.com" : 4
            }
        ]

VotedUserDTO为空。 VotedUsers是键值对中包含对象的数据的列表。

我没有提到ReviewsDTO,因为它已被完美映射。如何映射votedUsers部分? 注意:我正在使用Spring进行开发。

3 个答案:

答案 0 :(得分:0)

来自JSON的一些观察结果
1. Json在设计时应牢记固定键和可变值。
2.由于在上述情况下,键和值都是可变的,因此我们可以使用Map
所以最后的解决办法是
private List<VotedUsersDTO> votedUsers;更改为private List<Map<String, Integer>> votedUsers

答案 1 :(得分:0)

private List<Map<String, String>> votedUsers;

请勿使用明确的votedUser DTO。

答案 2 :(得分:-1)

votedUsers应该是VotedUsersDTO的列表。
如果您在JSON中查看VotedUsersDTO:

{
"abc\\bis@cdf.com" : 4
}

这意味着存在一个字段abc\\bis@cdf.com,您希望该字段的值为4。 这不符合DTO定义中的idvotedUser映射。

相关问题