我正在尝试使用以下REST HAL响应中的实体列表:

    {
  "_embedded" : {
    "posts" : [ {
      "branch" : 1,
      "article" : "aaaaaaa",
      "featuredImage" : "aaaaaaa",
      "authorId" : 1,
      "datePublished" : "2020-05-05T09:11:13.336+0000",
      "commentsEnabled" : true,
      "enabled" : false,
      "views" : 0,
      "snippetTitle" : null,
      "snippetDescription" : null,
      "comments" : null,
      "_links" : {
        "self" : {
          "href" : "http://localhost:8081/posts/1"
        },
        "post" : {
          "href" : "http://localhost:8081/posts/1"
        },
        "categories" : {
          "href" : "http://localhost:8081/posts/1/categories"
        }
      }
    }, {
      "branch" : 1,
      "article" : "aaaaaaa",
      "featuredImage" : "aaaaaaa",
      "authorId" : 1,
      "datePublished" : "2020-05-05T10:45:15.999+0000",
      "commentsEnabled" : true,
      "enabled" : false,
      "views" : 0,
      "snippetTitle" : null,
      "snippetDescription" : null,
      "comments" : null,
      "_links" : {
        "self" : {
          "href" : "http://localhost:8081/posts/3"
        },
        "post" : {
          "href" : "http://localhost:8081/posts/3"
        },
        "categories" : {
          "href" : "http://localhost:8081/posts/3/categories"
        }
      }
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8081/posts/search/byAuthorId?authorId=1&page=0&size=10"
    }
  },
  "page" : {
    "size" : 10,
    "totalElements" : 3,
    "totalPages" : 1,
    "number" : 0
  }
}


我想将这些实体映射到此类:

@Setter
@Getter
@AllArgsConstructor
public class Post {
  private int id;
  private int branch;
  private String article;
  private Date datePublished;
  private String featuredImage;
  private Boolean commentsEnabled;
  private Boolean enabled;
  private int views;
  private String snippetTitle;
  private String snippetDescription;
}


但是,我不断收到错误:


无法识别的字段“ _embedded”(类
org.springframework.hateoas.PagedModel),未标记为可忽略(3
已知属性:“链接”,“页面”,“内容”])


使用此代码:

  ObjectMapper mapper = new ObjectMapper();
  MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();

  messageConverter.setSupportedMediaTypes(MediaType.parseMediaTypes("application/hal+json"));
  messageConverter.setObjectMapper(mapper);

  ResponseEntity<PagedModel<Post>> responseEntity =
    new RestTemplate(Arrays.asList(messageConverter)).exchange(uri, HttpMethod.GET, HttpEntity.EMPTY, new ParameterizedTypeReference<PagedModel<Post>>() {});


这些版本是:

Jackson-databind版本:2.11.0

Spring-hateoas版本:1.0.5.RELEASE

任何帮助,将不胜感激!

最佳答案

响应结构看起来像PagedResources<T>类型。

org.springframework.hateoas.PagedResources中使用ParameterizedTypeReference

ResponseEntity<PagedResources<Post>> responseEntity =
    new RestTemplate(Arrays.asList(messageConverter)).exchange(uri, HttpMethod.GET, HttpEntity.EMPTY, new ParameterizedTypeReference<PagedResources<Post>>() {});

10-07 20:16