问题描述
我想通过Spring Rest模板编辑列表: List< Pojo>
对象。
I'm trying to marshal a list: List<Pojo>
objects via the Spring Rest Template.
我可以传递简单的 Pojo
对象,但我找不到任何文档描述如何发送 List< Pojo>
object。
I can pass along simple Pojo
objects, but I can't find any documentation that describes how to send a List<Pojo>
objects.
Spring使用Jackson JSON来实现 HttpMessageConverter
。 jackson的文档包括:
Spring is using Jackson JSON to implement the HttpMessageConverter
. The jackson documentation covers this:
因此,如果你想将数据绑定到
Map< String,User>
,你需要使用:
So if you want to bind data into a Map<String,User>
you will need to use:
Map< String,User> result = mapper.readValue(src,new TypeReference< Map< String,User>>(){});
c $ c> TypeReference 只需要
传递泛型类型定义(通过
在这种情况下为任意内部类):
重要的部分是
< Map< String,User>>
定义要绑定到的
类型。
where TypeReference
is only needed to pass generic type definition (via anynomous inner class in this case): the important part is <Map<String,User>>
which defines type to bind to.
这可以在Spring模板中完成吗?我看了一下代码,它让我不是,但也许我只是不知道一些技巧。
Can this be accomplished in the Spring template? I took a glance at the code and it makes me thing not, but maybe I just don't know some trick.
解决方案
由于以下有用的答案,最终的解决方案是不发送列表,而是发送单个对象扩展一个List,例如: class PojoList extends ArrayList< Pojo>
。 Spring可以成功地编组这个对象,它完成了与发送一个 List< Pojo>
相同的东西,虽然它不太清楚一个解决方案。我也在春天发布了一个JIRA,他们在他们的 HttpMessageConverter
界面中解决这个缺点。
The ultimate solution, thanks to the helpful answers below, was to not send a List, but rather send a single object which simply extends a List, such as: class PojoList extends ArrayList<Pojo>
. Spring can successfully marshal this Object, and it accomplishes the same thing as sending a List<Pojo>
, though it be a little less clean of a solution. I also posted a JIRA in spring for them to address this shortcoming in their HttpMessageConverter
interface.
推荐答案
如果我阅读了右键,您必须创建并注册 MappingJacksonHttpMessageConverter
的子类方法:
If I read the docs for MappingJacksonHttpMessageConverter
right, you will have to create and register a subclass of MappingJacksonHttpMessageConverter
and override the getJavaType(Class<?>)
method:
protected JavaType getJavaType(Class<?> clazz) {
if (List.class.isAssignableFrom(clazz)) {
return TypeFactory.collectionType(ArrayList.class, MyBean.class);
} else {
return super.getJavaType(clazz);
}
}
这篇关于Spring / json:转换类型化的集合,如List< MyPojo>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!