How to remove the “_embedded” property in Spring HATEOAS

筅森魡賤 提交于 2019-11-30 03:53:12

As the documentation says

application/hal+json responses should be sent to requests that accept application/json

In order to omit _embedded in you response you'll need to add

spring.hateoas.use-hal-as-default-json-media-type=false

to application.properties.

Jumbo N. Dejcharoen

Adding this Accept header to the request:

Accept : application/x-spring-data-verbose+json

I close HAL feature, because it is hard to using Resources/Resource by restTemplate. I disable this feature by following code:

public class SpringRestConfiguration implements RepositoryRestConfigurer {
    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {

        config.setDefaultMediaType(MediaType.APPLICATION_JSON);
        config.useHalAsDefaultJsonMediaType(false);
    }
}

It work for me. HAL is good if there are more support with restTemplate.

You can use this code in the service

  constructor(
    private httpClient: HttpClient
  ) { }

  retrieveAllStudents(){
    return this.httpClient.get<any[]>(`http://localhost:8080/students`);
  }

This will deal with the _embedded part of Json and extract the desired data.

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[];
     }
   );
 }
Stepan Mozyra

For those who use Spring Data, and consider it as a problem - solution is to set

spring.data.rest.defaultMediaType = application/json

in application properties. There still links will be available, but no _embedded any more.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!