RestTemplate解析返回的Page对象
【摘要】 RestTemplate解析返回的Page对象我的sping项目在做单元测试时有如下语句,ResponseEntity responseEntity = this.restTemplate.getForEntity("/v1/users?size=5", Page.class);其中,API/v1/users?size=5返回的是一个Page对象转成的JSON对象。该语句在执行时会报错,Can n
RestTemplate解析返回的Page对象
我的sping项目在做单元测试时有如下语句,
ResponseEntity responseEntity = this.restTemplate.getForEntity("/v1/users?size=5", Page.class);
其中,API/v1/users?size=5
返回的是一个Page对象转成的JSON对象。
该语句在执行时会报错,
Can not construct instance of org.springframework.data.domain.Page: abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
错误原因写得还算清晰,说不能实例化Page对象(将返回的JSON转回Java对象)。
由于Page是个抽象类,Jackson无法实例化它的对象。报错中给出了几条建议:
to be mapped to concrete types
have custom deserializer
contain additional type information。
选择2,3太麻烦。因此对于Rest server返回的Page对象,我们可以用具体的类型来实例化它。然而,spring中的实现类PageImpl也不能使用,因为该类没有无参构造函数,也没有被@JsonCreator
标记的构造函数。因此,我们需要自己写一个实现Page抽象类的具体类型。代码如下:
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import java.util.ArrayList;
import java.util.List;
public class RestPageImpl<T> extends PageImpl<T>{
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public RestPageImpl(@JsonProperty("content") List<T> content,
@JsonProperty("number") int page,
@JsonProperty("size") int size,
@JsonProperty("totalElements") long total) {
super(content, new PageRequest(page, size), total);
}
public RestPageImpl(List<T> content, Pageable pageable, long total) {
super(content, pageable, total);
}
public RestPageImpl(List<T> content) {
super(content);
}
public RestPageImpl() {
super(new ArrayList());
}
}
这个类只是为了在单元测试时使用,因此加在test的包中就可以了。最后修改成如下语句就不会报错了:
ResponseEntity responseEntity = this.restTemplate.getForEntity("/v1/users?size=5", CustomPageImpl.class);
参考
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)