jackson 反序列化string_使用Jackson从String反序列化ArrayList

I am using Spring's MappingJacksonHttpMessageConverter to convert JSON message to object in my controller.

class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">

For fields that are declared as ArrayList, if the json message contains a String instead, the following exception will be thrown:

org.springframework.http.converter.HttpMessageNotReadableException:

Could not read JSON: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token

An example would be the class definition below:

public class Product {

private String name;

private List images;

}

Where the incoming Json is:

{name:"Widget", images:"image1.jpg"}

AS you can see, this will produce the exception since image is expected to be an array.

I would like to make custom deserializer which is a bit more tolerant. If deserialization fails, create a ArrayList of a single element from the String. How would I go about injecting this into the MappingJacksonHttpMessageConverter or ObjectMapper?

I am not looking to use annotation to mark each and every ArrayList field so a custom deserialize could be used. I am looking for a way to overwrite the default deserializer to preform this function.

解决方案

Check out this article describing how to use the features of the jackson objectMapper to accomplish this.

For me adding the following solved this issue

jsonMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值