问题描述
我正在使用Spring的 RestTemplate
来使用Web服务,并使用 Jackson
进行反序列化。
I'm consuming a web service using Spring's RestTemplate
and deserializing with Jackson
.
在我来自服务器的JSON响应中,其中一个字段可以是对象或列表。意思是它可以是result:[{}]
或result:{}
。
In my JSON response from the server, one of the fields can be either an object or a list. meaning it can be either "result": [{}]
or "result": {}
.
有没有办法通过我反序列化的类型的注释来处理这类事情?将成员定义为 array []
或 List<>
并在第二个示例的情况下插入单个对象?
我可以写一个新的 HttpMessageConverter
来处理吗?
Is there a way to handle this kind of things by annotations on the type I'm deserializing to ? define the member as an array[]
or List<>
and insert a single object in case of the second example ?Can I write a new HttpMessageConverter
that will handle it ?
推荐答案
您可以使用Jackson的 ObjectMapper
中的配置标记来实现您想要的效果:
You can achieve what you want with a configuration flag in Jackson's ObjectMapper
:
ObjectMapper mapper = Jackson2ObjectMapperBuilder.json()
.featuresToEnable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
.build();
只需将此 ObjectMapper
实例设置为 RestTemplate
,如中所述,并在课程中进行反序列化to,总是使用一个集合,即列表
:
Just set this ObjectMapper
instance to your RestTemplate
as explained in this answer, and in the class you are deserializing to, always use a collection, i.e. a List
:
public class Response {
private List<Result> result;
// getter and setter
}
这篇关于杰克逊杰森将一个对象反序列化为一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!