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

时间:2015-08-10 13:06:30

标签: json spring spring-data-rest spring-hateoas spring-web

我正在使用RestTemplate来测试通过Spring DATA REST公开的API,在解析响应时我无法获取链接。其余模板配置了Jackson2HalModule支持的HttpConverter,请求的实体具有指向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);

现在,我希望链接在解析的响应对象中也可用,但情况并非如此,这是我获取响应的方式

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

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

但是场地链接断言失败

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

给出NullPointerException

1 个答案:

答案 0 :(得分:2)

您没有使用halConverter注册RestTemplate,因为您只查找现有的halConverter并将RestTemplate加上一个永远不会进入的任意列表再次for /F "tokens=1,2,3 delims=;" %%i in (file.txt) do call :process %%i %%j %%k goto :ENDPOINT :process echo %1 echo %2 echo %3