我使用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字段,因此可以使用自定义反序列化. 我正在寻找一种方法来覆盖默认的反序列化器以执行此功能.