使用 spring-hateoas 反序列化包含(_links和_embedded)的 JSON
2022-09-02 10:38:28
我正在尝试调用返回此表单数据的非常简单的json Webservice:
{
"_embedded": {
"users": [{
"identifier": "1",
"firstName": "John",
"lastName": "Doe",
"_links": {
"self": {
"href": "http://localhost:8080/test/users/1"
}
}
},
{
"identifier": "2",
"firstName": "Paul",
"lastName": "Smith",
"_links": {
"self": {
"href": "http://localhost:8080/test/users/2"
}
}
}]
},
"_links": {
"self": {
"href": "http://localhost:8080/test/users"
}
},
"page": {
"size": 20,
"totalElements": 2,
"totalPages": 1,
"number": 0
}
}
如您所见,它非常简单。我在解析链接时没有问题,让我的POJO扩展了ResourceSupport。以下是它们的外观:
UsersJson (根元素)
public class UsersJson extends ResourceSupport {
private List<UserJson> users;
[... getters and setters ...]
}
用户杰森
public class UserJson extends ResourceSupport {
private Long identifier;
private String firstName;
private String lastName;
[... getters and setters ...]
}
问题是,我期望jackson和spring足够聪明,可以解析_embedded属性并填充我的UsersJson.users属性,但事实并非如此。
我尝试了在互联网上找到的各种东西,但我唯一能正常工作的就是创建一个新的类作为_embedded包装器:
UsersJson (根元素)
public class UsersJson extends ResourceSupport {
@JsonProperty("_embedded")
private UsersEmbeddedListJson embedded;
[... getters and setters ...]
}
嵌入式“包装器”
public class UsersEmbeddedListJson extends ResourceSupport {
private List<UserJson> users;
[... getters and setters ...]
}
它有效,但我发现它很丑陋。
然而,我虽然RestTemplate的以下配置可以工作(特别是当我在Jackson2HalModule中看到IndembedMapper时),但它没有:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.registerModule(new Jackson2HalModule());
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(MediaType.parseMediaTypes("application/hal+json"));
converter.setObjectMapper(mapper);
RestTemplate restTemplate = new RestTemplate(Collections.singletonList(converter));
ResponseEntity<UsersJson> result = restTemplate.getForEntity("http://localhost:8089/test/users", UsersJson.class, new HashMap<String, Object>());
System.out.println(result);
有人能告诉我我错过了什么吗?