杰克逊convertValue到列表,但返回null

时间:2018-12-17 11:12:45

标签: java json jackson

json字符串如下:

[
   {
     "id":1545043316459,
     "user_id":127118102570729472,
     "username":"abcd",
     "phone":"12413453563",
     "password":"b6b33aad5c337315d4ac5a34d82db990cfaf22e5eefe27220b6827d5e66ad8b4",
     "license":"12351331",
     "plate":"abcdef",
     "avatar":"",
     "approval":0,
     "balance":0.0
   }
]

当我使用ObjectMapper.convertValue()将此json转换为List<User>时,该方法返回null。但是,当我将“批准”字段更改为1时,转换成功。
User的构造函数如下:

@JsonCreator
public User(@JsonProperty("user_id") long userId, @JsonProperty("username") String username, @JsonProperty("password") String password, @JsonProperty("avatar") String avatar,
                @JsonProperty("phone") String phone, @JsonProperty("license") String license, @JsonProperty("plate") String plate, @JsonProperty("approval") int approval,
                @JsonProperty("balance") BigDecimal balance) {
   this.userId = userId;
   this.username = username;
   this.password = password;
   this.avatar = avatar;
   this.phone = phone;
   this.license = license;
   this.plate = plate;
   this.balance = balance;
   this.approval = approval;
}

我已将@JsonIgnoreProperties(ignoreUnknown = true)应用于课程。

1 个答案:

答案 0 :(得分:2)

Jackson会忽略具有默认值的原始类型。

要解决此问题,您可以:

  1. 批准

    字段上添加注释
    @JsonInclude(Include.NON_DEFAULT)
    
  2. 将类型从int更改为Integer

解决方案由您决定