具有分页API的Spring RestTemplate [英] Spring RestTemplate with paginated API
本文介绍了具有分页API的Spring RestTemplate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们的REST API在Pages中返回结果.这是一个控制器的例子
Our REST APIs are returning results in Pages. Here is an example of one Controller
@RequestMapping(value = "/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
@ResponseStatus(HttpStatus.OK)
public Page<MyObject> findAll(Pageable pageable) {
...
}
是否有一种简单的方法可以通过RestTemplate使用该API?
Is there an easy way to consume that API with RestTemplate?
如果我们这样做
ParameterizedTypeReference<Page<MyObject>> responseType = new ParameterizedTypeReference<Page<MyObject>>() { };
ResponseEntity<Page<MyObject>> result = restTemplate.exchange(url, HttpMethod.GET, null/*httpEntity*/, responseType);
List<MyObject> searchResult = result.getBody().getContent();
它引发异常
org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not construct instance of org.springframework.data.domain.Page,
problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information at [Source: java.io.PushbackInputStream@3be1e1f2; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of org.springframework.data.domain.Page, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information
提前谢谢
推荐答案
将读取Rest API响应的代码更改为;
Changed the code reading the Rest API response as;
ParameterizedTypeReference<RestResponsePage<MyObject>> responseType = new ParameterizedTypeReference<RestResponsePage<MyObject>>() { };
ResponseEntity<RestResponsePage<MyObject>> result = restTemplate.exchange(url, HttpMethod.GET, null/*httpEntity*/, responseType);
List<MyObject> searchResult = result.getBody().getContent();
这是我为RestResponsePage创建的类</p>
And here is the class I created for RestResponsePage
package com.basf.gb.cube.seq.vaadinui.util;
import java.util.ArrayList;
import java.util.List;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
public class RestResponsePage<T> extends PageImpl<T>{
private static final long serialVersionUID = 3248189030448292002L;
public RestResponsePage(List<T> content, Pageable pageable, long total) {
super(content, pageable, total);
// TODO Auto-generated constructor stub
}
public RestResponsePage(List<T> content) {
super(content);
// TODO Auto-generated constructor stub
}
/* PageImpl does not have an empty constructor and this was causing an issue for RestTemplate to cast the Rest API response
* back to Page.
*/
public RestResponsePage() {
super(new ArrayList<T>());
}
}
这篇关于具有分页API的Spring RestTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文