Spring Hateoas:使用 RESTTemplate 时,内容始终为空

Spring Hateoas: When consuming with RESTTemplate then content is always empty

我有一个生成 hateoas 资源的端点:

@GetMapping()
public ResponseEntity<PagedModel<EntityModel<Content>>> getContent(
    @RequestParam(defaultValue = "0") final Integer page,
    @RequestParam(defaultValue = "10") final Integer size) {
        return ResponsEntity
            .ok()
            .body(service.getContent(page, size));
}

当我使用浏览器调用此端点时,我得到以下结果:

{
    "_embedded" : {
        "contents": [
            ...,
            ...
        ]
    },
    "_links": {
        "self": {
            "href": "http://localhost:8080/contents?page=0&size=10"
        }
    },
    "page": {
        "size": 10,
        "totalElements": 2,
        "totalPages": 1,
        "number": 0
    }
}

没关系。但是当我使用另一个 spring 服务使用 rest 模板使用端点时:

ResponseEntity response = restTemplate.exchange(
    url, 
    GET, 
    null,
    new ParameterizedTypeReference<PagedModel<EntityModel<Content>>>() {}));

LOG.info(response);

我得到以下输出:

<200, PagedResource { content: [], metadata: Metadata { number: 0, total pages: 1, total elements: 2, size: 10}, links: } ...

内容始终为空。

我需要做什么才能正确反序列化 PagedResource?

必须添加以下配置:

@Configuration
public class ServiceConfiguration {

  @Bean
  public ObjectMapper objectMapper() {
    final ObjectMapper objectMapper = new ObjectMapper();

    objectMapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.registerModule(new Jackson2HalModule());

    return objectMapper;
  }

  @Bean
  public MappingJackson2HttpMessageConverter converter() {
    final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();

    converter.setSupportedMediaTypes(singletonList(HAL_JSON));
    converter.setObjectMapper(objectMapper());

    return converter;
  }

  @Bean
  public RestTemplate restTemplate(final RestTemplateBuilder builder) {
    return builder.messageConverters(converter()).build();
  }
}