【发布时间】:2018-11-22 09:01:59
【问题描述】:
我需要调用一个需要Pageable 字段的端点:
@GetMapping
public Page<ProductDTO> listProducts(Pageable pageable) {
return productService.findProducts(pageable);
}
在我的测试中,我有这个代码:
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("page", String.valueOf(0));
URI url = defaultURI(port, "/products", parameters);
ParameterizedTypeReference<RestResponsePage<ProductDTO>> type = new ParameterizedTypeReference<RestResponsePage<ProductDTO>>() {};
ResponseEntity<RestResponsePage<ProductDTO>> response = restTemplate.exchange(url.toString(), HttpMethod.GET, httpEntity, type);
PageImpl 不包含默认构造函数,因此为了避免这个问题,我创建了一个类似以下的类来传递给ParameterizedTypeReference:
@JsonIgnoreProperties(ignoreUnknown = true) @Getter @Setter
public class RestResponsePage<T> extends PageImpl<T> implements Serializable {
private static final long serialVersionUID = 3844794233375694591L;
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public RestResponsePage(@JsonProperty("content") List<T> content,
@JsonProperty("number") int page,
@JsonProperty("size") int size,
@JsonProperty("totalElements") long totalElements) {
super(content, new PageRequest(page, size), totalElements);
}
public RestResponsePage(List<T> content, Pageable pageable, long totalElements) {
super(content, pageable, totalElements);
}
public RestResponsePage(List<T> content) {
super(content);
}
public RestResponsePage() {
super(new ArrayList<T>());
}
}
问题是我仍然收到以下错误:
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of org.springframework.data.domain.Pageable: abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
at [Source: java.io.PushbackInputStream@75564689; line: 38, column: 16] (through reference chain: com.shaunyl.util.ResponsePageImpl["pageable"])
为什么它一直说我正在传递一个抽象类? ResponsePageImpl 是一个类而不是抽象类。
谢谢
【问题讨论】:
-
一个问题可能是您的 RestResponsePage 类是一个抽象类型。如果您查看stackoverflow.com/a/44895867/3362244,您会注意到HelperPage 类不是一般类型的。相反,它是一个通用类型抽象类的具体实现,Jackson 可以对其进行反序列化。这是它起作用的关键原因之一。
-
@jtcotton63 没有骰子,我得到了同样的错误。
-
你试过从类声明中删除
implements Serializable吗? -
@Venky 对我来说这行不通。
标签: java rest spring-boot jackson