java - Spring /json : Convert a typed collection like List<MyPojo>

标签 java spring collections spring-mvc jackson

我正在尝试编码一个列表: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/

相关文章:

java - JVM maxHeapSize 和 InitialHeapSize 未反射(reflect)在 htop 中

java - Hibernate 映射和唯一索引或主键违规

java - 创建遗留类的bean,无需修改,无需xml配置

java - 在另一个切面上下文中调用切面 - Spring AOP

java - 在Jhipster中创建与用户(jhiUser)的实体关系

java - DDL View 的 jooq 等价物是什么?

java - spring mvc属性文件中linux home的路径

java - "{}"是什么意思?什么时候 map 是空的?

c# - 从哈希表中读取匹配的记录到类对象中

java - 计算列表中元素的数量并将其附加到每个项目的末尾并维护要返回的列表中的插入顺序?