jos*_*e_p 17 rest spring spring-hateoas spring-boot
我正在使用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"
}
}
}
]
}
}
Run Code Online (Sandbox Code Playgroud)
我希望响应是这样的:
{
"_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"
}
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
我的技术控制器:
@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;
}
Run Code Online (Sandbox Code Playgroud)
配置类具有注释@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL).
没有"_embedded"产生响应的最佳方法是什么?
正如文档所说
application/hal + json响应应发送给接受application/json的请求
为了省略_embedded您的回复,您需要添加
spring.hateoas.use-hal-as-default-json-media-type=false
Run Code Online (Sandbox Code Playgroud)
到application.properties.
我关闭了 HAL 功能,因为很难通过 restTemplate 使用资源/资源。我通过以下代码禁用此功能:
public class SpringRestConfiguration implements RepositoryRestConfigurer {
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.setDefaultMediaType(MediaType.APPLICATION_JSON);
config.useHalAsDefaultJsonMediaType(false);
}
}
Run Code Online (Sandbox Code Playgroud)
它对我有用。如果restTemplate 有更多支持,HAL 会很好。
小智 6
将此Accept标头添加到请求中:
Accept : application/x-spring-data-verbose+json
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13822 次 |
| 最近记录: |