在Projection REST响应中重复_links键

时间:2018-06-11 09:43:43

标签: java spring-boot spring-hateoas

在投影的Json框架中添加我的链接我添加了以下类:

@Component
public class ResumeEntityProjectionResourceProcessor implements ResourceProcessor<Resource<ResumeEntity>> {

@Override
public Resource<ResumeEntity> process(Resource<ResumeEntity> resource) {

    UriComponents uriComponents = ServletUriComponentsBuilder.fromCurrentContextPath()
            .path("/api/entities/search/findEntities")
            .buildAndExpand(Long.toString(resource.getContent().getId()));
    resource.add(new Link(uriComponents.toUriString(), "findEntities"));

    return resource;
}

我现在作为返回值的问题是两个键“_links”,一个是默认链接加上我的链接,另一个是我的链接。

{
"_embedded": {
    "entities": [{
            "id": 1696,
            "reference": "aaaaaa",
            "_links": {
                "self": {
                    "href": "http://localhost:8080/myProject/api/entities/1696{?projection}",
                    "templated": true
                },
                "findByParametresValide": {
                    "href": "http://localhost:8080/myProject/api/entities/search/findEntities"
                }
            },
            "_links": {
                "findByParametresValide": {
                    "href": "http://localhost:8080/myProject/api/entities/search/findEntities"
                }
            }
        }
    ]
}
}

我是如何只保留第一个标签的?

预期结果

{
"_embedded": {
    "entities": [{
            "id": 1696,
            "reference": "aaaaaa",
            "_links": {
                "self": {
                    "href": "http://localhost:8080/myProject/api/entities/1696{?projection}",
                    "templated": true
                },
                "findByParametresValide": {
                    "href": "http://localhost:8080/myProject/api/entities/search/findEntities"
                }
            }
        }
    ]
}
}

感谢

1 个答案:

答案 0 :(得分:0)

@Override
public Resource<ResumeEntity> process(Resource<ResumeEntity> resource) {
if (resource.getLinks().isEmpty()) { 
return resource; 
}
    UriComponents uriComponents = ServletUriComponentsBuilder.fromCurrentContextPath()
            .path("/api/entities/search/findEntities")
            .buildAndExpand(Long.toString(resource.getContent().getId()));
    resource.add(new Link(uriComponents.toUriString(), "findEntities"));

    return resource;
}