【发布时间】:2015-05-02 17:05:30
【问题描述】:
我正在使用 Spring Boot 和 HATEOAS 构建一个 REST API,当我的 API 返回一个集合时,它被包装在一个“_embedded”属性中,如下所示:
{
"_links":{
"self":{
"href":"http://localhost:8080/technologies"
}
},
"_embedded":{
"technologies":[
{
"id":1,
"description":"A",
"_links":{
"self":{
"href":"http://localhost:8080/technologies/1"
}
}
},
{
"id":2,
"description":"B",
"_links":{
"self":{
"href":"http://localhost:8080/technologies/2"
}
}
}
]
}
}
我希望回复是这样的:
{
"_links":{
"self":{
"href":"http://localhost:8080/technologies"
}
},
"technologies":[
{
"id":1,
"description":"A",
"_links":{
"self":{
"href":"http://localhost:8080/technologies/1"
}
}
},
{
"id":2,
"description":"B",
"_links":{
"self":{
"href":"http://localhost:8080/technologies/2"
}
}
}
]
}
我的技术控制器:
@RestController
@ExposesResourceFor(Technology.class)
@RequestMapping(value = "/technologies")
public class TechnologiesController {
...
@ResquestMapping(method = RequestMethod.GET, produces = "application/vnd.xpto-technologies.text+json")
public Resources<Resource<Technology>> getAllTechnologies() {
List<Technology> technologies = technologyGateway.getAllTechnologies();
Resources<<Resource<Technology>> resources = new Resources<Resource<Technology>>(technologyResourceAssembler.toResources(technologies));
resources.add(linkTo(methodOn(TechnologiesController.class).getAllTechnologies()).withSelfRel());
return resources;
}
配置类有注解@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)。
在没有“_embedded”的情况下产生响应的最佳方法是什么?
【问题讨论】:
-
如果您从响应中删除
_embedded,则响应将不再是有效的 HAL。您要么需要坚持使用_embedded,要么使用其他媒体类型。 -
HAL 草案显示“保留的“_embedded”属性是可选的”
-
它是可选的,因为资源不必具有任何嵌入式资源。但是,如果确实如此,那么它们应该在
_embedded之下。 -
我也遇到了同样的问题。我在一个对象上有一个投影,并将其限制为仅显示名称。问题是有超过 20 个关系,所以 _embedded 对象很大。我也没有找到克服这个问题的好方法。
标签: spring rest spring-boot spring-hateoas