我正在使用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”产生响应的最佳方法是什么?
正如documentation所说
application / hal + json响应应发送给接受application / json的请求
为了在你的回复中省略_embedded
,你需要添加
spring.hateoas.use-hal-as-default-json-media-type=false
到application.properties
。
将Accept
标头添加到请求中:
Accept : application/x-spring-data-verbose+json
我关闭了HAL功能,因为restTemplate很难使用Resources / Resource。我通过以下代码禁用此功能:
public class SpringRestConfiguration implements RepositoryRestConfigurer {
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.setDefaultMediaType(MediaType.APPLICATION_JSON);
config.useHalAsDefaultJsonMediaType(false);
}
}
它对我有用。如果有更多的restTemplate支持,HAL是好的。
您可以在服务中使用此代码
constructor(
private httpClient: HttpClient
) { }
retrieveAllStudents(){
return this.httpClient.get<any[]>(`http://localhost:8080/students`);
}
这将处理Json的_embedded部分并提取所需的数据。
export class ListStudentsComponent implements OnInit {
// declaring variables to be used
student: Student;
students: Student[];
message: string;
// injecting student service into the constuctor
constructor(
private studentService: StudentService,
) { }
ngOnInit() {
this.refreshStudents();
}
refreshStudents(){
this.studentService.retrieveAllStudents().subscribe(
response => {
console.log(response);
this.students = response._embedded.students as Student[];
}
);
}
对于那些使用Spring Data并将其视为问题的人 - 解决方案就是设置
spring.data.rest.defaultMediaType = application/json
在应用程序属性中仍有链接可用,但不再嵌入_embedded。