使用spring-hateoas反序列化包含(_links和_embedded)的JSON

问题描述 投票:12回答:3

我试图调用非常简单的json Web服务,返回此表单的数据:

{
    "_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 ...]
}

UserJson

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中看到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);

有人能告诉我我错过了什么吗?

java json spring jackson spring-hateoas
3个回答
3
投票

最后,我发现了一种更好的方法来使用那些application / hal + json API。

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();

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

这是我添加的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>

2
投票

不得不把这个添加到我的DTO:

@JsonProperty("_links")
public void setLinks(final Map<String, Link> links) {
    links.forEach((label, link) ->  add(link.withRel(label)) );
}

因为ResourceSupport没有链接的POJO标准/ Json信号设置器/构造函数


0
投票

我不得不使用自定义setter扩展我的DTO POJO,使用jackson作为mapper解析REST客户端中Spring Hateos的生成输出:

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]));
                    }
                }
        );
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.