有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用Spring RestTemplate使用分页API

我想使用分页的API。该API由使用SpringBoot创建的端点提供。在寻找解决方案时,我在StackOverflow上找到了thispost

几乎每个答案都建议创建一个要解析的POJO。但由于这是一个标准问题,因此应该有一个由框架支持的标准解决方案。在上面提到的帖子中有一个Vladimir Mitev的答案。他建议使用ParameterizedTypeReference<PagedResources<T>>。为了我的目的,我接受了他的剪发并更改了类型T

restTemplate.exchange(targetUrl, HttpMethod.GET, requestEntity, new ParameterizedTypeReference<PagedResources<String>>() {});

这有助于获取页面内容。但这里的问题是,提供的元数据一直为空。因此,由于我没有获得关于totalPages的信息,因此我无法遍历这些页面。我是否正确定义了ResponseType?清除bug使我发现调用了PagedResources的默认构造函数,因此PageMetadata对象从未设置过

下面我将描述我是如何解决这个问题的。也许这有助于面对同样问题的其他人

使用分页API的简单方法是:

restTemplate.exchange(targetUrl, HttpMethod.GET, requestEntity, String.class);

这让我们了解了底层数据结构,如下所示

<200,
{
   "content":[
      "Data1",
      "Data2",
      "Data3"
   ],
   "pageable":{
      "sort":{
         "sorted":false,
         "unsorted":true,
         "empty":true
      },
      "offset":0,
      "pageSize":20,
      "pageNumber":0,
      "paged":true,
      "unpaged":false
   },
   "number":0,
   "sort":{
      "sorted":false,
      "unsorted":true,
      "empty":true
   },
   "size":20,
   "first":true,
   "numberOfElements":20,
   "totalPages":5,
   "totalElements":90,
   "last":false,
   "empty":false
},
[
   Cache-Control:"no-cache, no-store, max-age=0, must
-revalidate",
   Content-Type:"application/json;charset=UTF-8",
   Date:"Thu, 20 Jun 2019 17:38:18 GMT",
   Expires:"0",
   Pragma:"no-cache",
   Server:"nginx/1.15.10",
   X-Content-Type-Options:"nosniff"

它看起来像一个标准的spring分页响应对象。所以应该有一种方法可以直接将这个响应转换成某种预定义的对象

因此,我尝试更改ResponseType参数: Page.class导致

org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class org.springframework.data.domain.Page]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of org.springframework.data.domain.Page (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information

{}和{cd7}

org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class org.springframework.data.domain.PageImpl]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of org.springframework.data.domain.PageImpl (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)

因此必须有另一个ResponseType来解析响应


共 (0) 个答案