使用Jackson从String反序列化ArrayList [英] Deserialize ArrayList from String using Jackson

查看:1118
本文介绍了使用Jackson从String反序列化ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Spring的MappingJacksonHttpMessageConverter将JSON消息转换为控制器中的对象。

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

<bean id="jsonConverter"
    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <property name="prefixJson" value="false" />
    <property name="supportedMediaTypes" value="application/json" />
</bean>

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jsonConverter" />
        </list>
    </property>
</bean>

对于声明为ArrayList的字段,如果json消息包含字符串,则以下异常将抛出:

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

以下是类定义的示例:

public class Product {
   private String name;
   private List<String> images;
}

收到的Json是:

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

如您所见,这将产生异常,因为图像应该是一个数组。

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

我想制作自定义反序列化器有点宽容。如果反序列化失败,请从String中创建单个元素的ArrayList。我如何将其注入MappingJacksonHttpMessageConverter或ObjectMapper?

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?

我不打算使用注释来标记每个ArrayList字段,因此可以使用自定义反序列化。 我正在寻找一种方法来覆盖默认的反序列化器以执行此功能。

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.

推荐答案

退房本文描述了如何使用jackson objectMapper的功能来实现这一目标。

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

https:/ /github.com/FasterXML/jackson-dataformat-xml/issues/21

对我来说,添加以下内容解决了这个问题

For me adding the following solved this issue

jsonMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

这篇关于使用Jackson从String反序列化ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆