我正在尝试编码一个列表:List<Pojo>
通过 Spring Rest 模板创建对象。
我可以简单地传递 Pojo
对象,但我找不到任何描述如何发送 List<Pojo>
的文档对象。
Spring 正在使用 Jackson JSON 来实现 HttpMessageConverter
. jackson 文档涵盖了这一点:
In addition to binding to POJOs and "simple" types, there is one additional variant: that of binding to generic (typed) containers. This case requires special handling due to so-called Type Erasure (used by Java to implement generics in somewhat backwards compatible way), which prevents you from using something like
Collection<String>.class
(which does not compile).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>>() {});
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 模板中完成吗?我看了一眼代码,这让我不以为然,但也许我只是不知道一些技巧。
解决方案
由于以下有用的答案,最终的解决方案是不发送列表,而是发送一个简单地扩展列表的对象,例如:class PojoList extends ArrayList<Pojo>
. Spring 可以成功地编码这个对象,它完成与发送 List<Pojo>
相同的事情。 ,尽管它的解决方案不太干净。我还在 Spring 发布了一个 JIRA,让他们在他们的 HttpMessageConverter
中解决这个缺点。界面。
最佳答案
在 Spring 3.2现在支持在 RestTemplate
上使用新的 exchange()
方法的泛型类型:
ParameterizedTypeReference<List<MyBean>> typeRef = new ParameterizedTypeReference<List<MyBean>>() {};
ResponseEntity<List<MyBean>> response = template.exchange("http://example.com", HttpMethod.GET, null, typeRef);
像魅力一样工作!
关于java - Spring /json : Convert a typed collection like List<MyPojo>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6173182/