[英]Deserialize JSON containing (_links and _embedded) using spring-hateoas
I am trying to invoque very simple json webservices that return data of this form: 我试图invoque非常简单的json webservices返回此表单的数据:
{
"_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
}
}
As you can see, it is pretty straight forward. 正如您所看到的,它非常直接。 I have no problems parsing the links, having my POJOs extending form ResourceSupport.
解析链接没有问题,我的POJO从ResourceSupport扩展。 Here is what they look like:
这是他们的样子:
UsersJson (the root element) UsersJson(根元素)
public class UsersJson extends ResourceSupport {
private List<UserJson> users;
[... getters and setters ...]
}
UserJson UserJson
public class UserJson extends ResourceSupport {
private Long identifier;
private String firstName;
private String lastName;
[... getters and setters ...]
}
The thing is that I was expecting jackson and spring to be smart enough to parse the _embedded property and populate my UsersJson.users attribute but it isn't. 问题是我期待jackson和spring足够智能来解析_embedded属性并填充我的UsersJson.users属性,但事实并非如此。
I tried various things I found on the internet but the only thing I could get to work properly was to create a new class acting as an _embedded wrapper: 我尝试了在互联网上找到的各种各样的东西,但我唯一可以正常工作的是创建一个充当_embedded包装器的新类:
UsersJson (the root element) UsersJson(根元素)
public class UsersJson extends ResourceSupport {
@JsonProperty("_embedded")
private UsersEmbeddedListJson embedded;
[... getters and setters ...]
}
Embedded "wrapper" 嵌入式“包装”
public class UsersEmbeddedListJson extends ResourceSupport {
private List<UserJson> users;
[... getters and setters ...]
}
It works but I find it quite ugly. 它有效,但我发现它很难看。
Yet I though the following configuration of the RestTemplate would have worked (especially when I saw EmbeddedMapper in Jackson2HalModule), but it didn't: 然而,我虽然RestTemplate的以下配置会起作用(特别是当我在Jackson2HalModule中看到EmbeddedMapper时),但它没有:
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);
Can somebody tell me what I am missing? 有人能告诉我我错过了什么吗?
Finally, I found a better a way to consume those application/hal+json APIs. 最后,我发现了一种更好的方法来使用那些application / hal + json API。
Spring hateoas actually provides a client almost ready to use: org.springframework.hateoas.client.Traverson. Spring hateoas实际上提供了一个几乎可以使用的客户端:org.springframework.hateoas.client.Traverson。
Traverson traverson = new Traverson(new URI("http://localhost:8080/test"), MediaTypes.HAL_JSON);
TraversalBuilder tb = traverson.follow("users");
ParameterizedTypeReference<Resources<UserJson>> typeRefDevices = new ParameterizedTypeReference<Resources<UserJson>>() {};
Resources<UserJson> resUsers = tb.toObject(typeRefDevices);
Collection<UserJson> users= resUsers .getContent();
As you can see, I got rid UsersJson and UsersEmbeddedListJson. 如您所见,我摆脱了UsersJson和UsersEmbeddedListJson。
Here are the maven dependencies I added 这是我添加的maven依赖项
<dependency>
<groupId>org.springframework.hateoas</groupId>
<artifactId>spring-hateoas</artifactId>
<version>0.19.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.plugin</groupId>
<artifactId>spring-plugin-core</artifactId>
<version>1.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.0.0</version>
</dependency>
Had to add this to my DTO: 不得不把这个添加到我的DTO:
@JsonProperty("_links")
public void setLinks(final Map<String, Link> links) {
links.forEach((label, link) -> add(link.withRel(label)) );
}
since ResourceSupport has no POJO standard/Json-signaled setter/constructor for links 因为ResourceSupport没有链接的POJO标准/ Json信号设置器/构造函数
I had to extend my DTO POJO with a custom setter parsing the produced output of Spring Hateos in the REST client side by using jackson as mapper: 我不得不使用自定义setter扩展我的DTO POJO,使用jackson作为mapper解析REST客户端中Spring Hateos的生成输出:
HREF = "href" and REL is "rel" as constants. HREF = “href” , REL是“rel”作为常量。
@JsonProperty("link")
public void setLink(final List<Map<String, String>> links) {
if (links != null) {
links.forEach(l ->
{
final String[] rel = new String[1];
final String[] href = new String[1];
l.entrySet().stream().filter((e) -> e.getValue() != null)
.forEach(e -> {
if (e.getKey().equals(REL)) {
rel[0] = e.getValue();
}
if (e.getKey().equals(HREF)) {
href[0] = e.getValue();
}
});
if (rel[0] != null && href[0] != null) {
add(new Link(href[0], rel[0]));
}
}
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.