我正在使用 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 已按照本文中的建议进行配置,因为我们收到了 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