为什么 RestTemplate 从 HAL+JSON 响应中删除链接?

Why RestTemplate drops links from HAL+JSON response?

我正在使用 RestTemplate 测试通过 Spring DATA REST 公开的 API,但在解析响应时无法获得 links。其余模板配置有 Jackson2HalModule 支持的 HttpConverter,请求的实体具有 link 到 JSON 响应中出现的关联。

这是JSON

{
  "name" : "Hero @ Bangalore",
  "venue" : {
    "name" : "Wayne Manor",
    "address" : "1 MG Road",
    "city" : "Bangalore",
    "state" : "Karnataka",
    "pincode" : "560001"
  },
  "seatsAvailable" : 40,
  "workshopType" : "Batman Challengers",
  "date" : "2015-09-10",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/workshops/1{?projection}",
      "templated" : true
    },
    "venue" : {
      "href" : "http://localhost:8080/workshops/1/venue"
    }
  }
}

RestTemplate 配置为 adviced in this post,因为我们正在获取 HAL+JSON 响应

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.registerModule(new Jackson2HalModule());
MappingJackson2HttpMessageConverter halConverter = new MappingJackson2HttpMessageConverter();
halConverter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
halConverter.setObjectMapper(objectMapper);

restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> existingConverters = restTemplate.getMessageConverters();
List<HttpMessageConverter<?>> httpMessageConverters = new ArrayList<>();
httpMessageConverters.add(halMessageConverter);
httpMessageConverters.addAll(existingConverters);

现在,我希望 links 也可以在解析后的响应对象中使用,但事实并非如此,这是我获取响应的方式

ResponseEntity<Resource<Workshop>> workshopResource = 
restTemplate
        .exchange(DEFAULT_PROJECTION, HttpMethod.GET, null,
            new ParameterizedTypeReference<Resource<Workshop>>() {
            });

Workshop responseBody = workshopResource.getBody().getContent();

但是场地 link 的断言失败了

assertTrue(workshopResource.getBody().getLink("venue").equals(paulURI.toString()));  

给出一个NullPointerException

您没有将 halConverter 注册到 RestTemplate,因为您只是在查找现有的,然后将这些加上 halConverter 添加到一个永远不会生成的任意列表中再次进入RestTemplate