使用spring-hateoas反序列化包含(_links和_embedded)的JSON [英] Deserialize JSON containing (_links and _embedded) using spring-hateoas

查看:229
本文介绍了使用spring-hateoas反序列化包含(_links和_embedded)的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试开发非常简单的json网络服务,这些服务返回以下形式的数据:

I am trying to invoque very simple json webservices that return data of this form:

{
    "_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,因此解析链接没有问题. 它们是这样的:

As you can see, it is pretty straight forward. I have no problems parsing the links, having my POJOs extending form ResourceSupport. Here is what they look like:

UsersJson(根元素)

public class UsersJson extends ResourceSupport {
    private List<UserJson> users;

    [... getters and setters ...]
}

UserJson

public class UserJson extends ResourceSupport {

    private Long identifier;

    private String firstName;

    private String lastName;

    [... getters and setters ...]
}

事实是,我期望jackson和spring足够聪明,可以解析_embedded属性并填充我的UsersJson.users属性,但事实并非如此.

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.

我尝试了各种在互联网上发现的东西,但是我唯一能正常工作的是创建一个充当_embedded包装器的新类:

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:

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 ...]
}

它可以工作,但我觉得它很丑.

It works but I find it quite ugly.

但是我虽然可以使用RestTemplate的以下配置(特别是当我在Jackson2HalModule中看到EmbeddedMapper时),但是却没有:

Yet I though the following configuration of the RestTemplate would have worked (especially when I saw EmbeddedMapper in Jackson2HalModule), but it didn't:

        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?

推荐答案

最后,我找到了一种更好的使用这些application/hal + json API的方法.

Finally, I found a better a way to consume those application/hal+json APIs.

Spring hateoas实际上提供了一个几乎可以使用的客户端:org.springframework.hateoas.client.Traverson.

Spring hateoas actually provides a client almost ready to use: 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();

如您所见,我摆脱了UsersJson和UsersEmbeddedListJson.

As you can see, I got rid UsersJson and UsersEmbeddedListJson.

这是我添加的Maven依赖项

Here are the maven dependencies I added

    <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>

这篇关于使用spring-hateoas反序列化包含(_links和_embedded)的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆