我正在使用 Spring 的 MappingJacksonHttpMessageConverter 将 JSON 消息转换为 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,则会抛出以下异常:
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。我该如何将其注入(inject)到 MappingJacksonHttpMessageConverter 或 ObjectMapper 中?
我不打算使用注释来标记每个 ArrayList 字段,以便可以使用自定义反序列化。 我正在寻找一种方法来覆盖默认的反序列化器来执行此功能。
最佳答案
查看这篇文章,描述如何使用 jackson objectMapper 的功能来完成此任务。
https://github.com/FasterXML/jackson-dataformat-xml/issues/21
对我来说添加以下内容解决了这个问题
jsonMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
关于json - 使用 Jackson 从字符串反序列化 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10247639/