Spring REST, JSON “Can not handle managed/back reference 'defaultReference'” 415 Unsupported Media Type

前端 未结 7 1555
一整个雨季
一整个雨季 2020-12-28 17:16

I am trying to POST to http://localhost:9095/translators from an AngularJS front-end using Spring boot/Spring RestController backend.

I can do a GET and the response

7条回答
  •  臣服心动
    2020-12-28 18:01

    Another great way to solve this problem is with @JsonView. The idea is that you label your controller with a view name and then label the properties you wish to be displayed for that view. You specifically do not expose the backreferenced properties to the calling view. An extremely simplified example below:

    Imagine you had a 1 to 1 relationship like this. This would create a circular reference.

    @Entity
    public class Student {
    
      String name;
      Tutor tutor;
    
    }
    
    @Entity
    public class Tutor {
      String name;
      Student student;
    
    }
    

    You could now create views for them, almost the same way you do with @JsonIgnore and @JsonProperty.

    Step 1. Create arbitrary empty interfaces that you can use to tag your controllers.

    public class LearningController {
    
      @GetRequest("/tutors")
      @JsonView(TutorView.class) // create an empty interface with a useful name
      public Set tutors() {
        return tutorRepository.findAll()
      }
    
      @GetRequest("/students")
      @JsonView(StudentView.class) // create an empty interface with a useful name
      public Set students() {
        return studentRepository.findAll()
      }
    }
    

    Step 2. Label the properties you want to expose (in any related / referenced class) to the view, also using the @JsonView annotation.

    @Entity
    public class Student {
    
      @JsonView({StudentView.class, TutorView.class})
      String name;
    
      @JsonView({StudentView.class}) // Not visible to @TutorView (no backreference)
      Tutor tutor;
    
    }
    
    @Entity
    public class Tutor {
      @JsonView({StudentView.class, TutorView.class})
      String name;
      @JsonView(TutorView.class) // Not visible to @StudentView (no backreference)
      Student student;
    }
    

提交回复
热议问题