RestTemplate解析返回的Page对象

举报
晴天X风 发表于 2018/03/14 20:32:35 2018/03/14
【摘要】 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无法实例化它的对象。报错中给出了几条建议:

  1. to be mapped to concrete types

  2. have custom deserializer

  3. 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);


参考

stackoverflow_01

stackoverflow_02


【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。