小编典典

使用Jackson从String反序列化ArrayList

json

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

<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消息包含一个String,则将引发以下异常:

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"}

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

我想使自定义解串器更加宽容。如果反序列化失败,则从String中创建单个元素的ArrayList。我如何将其注入MappingJacksonHttpMessageConverter或ObjectMapper?

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


阅读 697

收藏
2020-07-27

共1个答案

小编典典

请查看本文,该文章描述了如何使用杰克逊objectMapper的功能来完成此任务。

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

对我来说,添加以下内容可以解决此问题

jsonMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
2020-07-27