ltf*_*hie 6 spring json jackson
我使用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>
Run Code Online (Sandbox Code Playgroud)
对于声明为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
Run Code Online (Sandbox Code Playgroud)
一个例子是下面的类定义:
public class Product {
private String name;
private List<String> images;
}
Run Code Online (Sandbox Code Playgroud)
传入Json的地方是:
{name:"Widget", images:"image1.jpg"}
Run Code Online (Sandbox Code Playgroud)
如您所见,这将产生异常,因为图像应该是一个数组.
我想制作一个更宽容的自定义反序列化器.如果反序列化失败,请从String中创建单个元素的ArrayList.我如何将其注入MappingJacksonHttpMessageConverter或ObjectMapper?
我不打算使用注释来标记每个ArrayList字段,因此可以使用自定义反序列化. 我正在寻找一种方法来覆盖默认的反序列化器以执行此功能.
小智 14
查看这篇文章,描述如何使用jackson objectMapper的功能来完成此任务.
https://github.com/FasterXML/jackson-dataformat-xml/issues/21
对我来说,添加以下内容解决了这个问题
jsonMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19376 次 |
| 最近记录: |