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

查看:31
本文介绍了使用 Jackson 从字符串反序列化 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 消息中包含 String,则会抛出以下异常:

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<String> images;
}

传入的 Json 在哪里:

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.

我想做一个更宽容的自定义解串器.如果反序列化失败,则从 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 从字符串反序列化 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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