【问题标题】:Ignoring Nested properties in Jackson OnDemand忽略 Jackson OnDemand 中的嵌套属性
【发布时间】:2017-09-22 21:30:15
【问题描述】:

我正在开发一个 Spring Boot 应用程序,其中 Hibernate 作为 ORM,Jackson 作为 JSON 序列化器。

我有三个模型对象和所有三个模型的 CRUD 操作。

Class Student{
     private Teacher teacher;  // Teacher of the student — to be fetched eagerly
    +Getter/Setter
}

class Teacher {
      private List<Subject> subject;  // List of subjects associated to that user— to be fetched eagerly
      +Getter/Setter 
}

class Subject {
     private long subjectId 
    //Other subject properties
    + Getter/Setter
}

每当我触发获取学生信息的请求时,我都会获得正确的教师信息,因为我还收到了对我来说不必要的主题信息。在我请求教师信息的同时,我需要主题信息应该与之相关联。如果我使用@JsonBackReference 作为主题,我会一直丢失它。我不确定如何实现这一目标。

提前感谢您的帮助!!

【问题讨论】:

标签: spring spring-boot jackson


【解决方案1】:

你也可以这样注释

Class Student{
    @JsonIgnoreProperties("subject")
    private Teacher teacher;  // Teacher of the student — to be fetched eagerly
}

【讨论】:

  • 这很有帮助。谢谢。
【解决方案2】:

您可以使用JSON Views

来自春季博客:

public class View {
  interface Summary {}
}

public class User {

  @JsonView(View.Summary.class)
  private Long id;

  @JsonView(View.Summary.class)
  private String firstname;

  @JsonView(View.Summary.class)
  private String lastname;

  private String email;
  private String address;
  private String postalCode;
  private String city;
  private String country;
}

public class Message {

  @JsonView(View.Summary.class)
  private Long id;

  @JsonView(View.Summary.class)
  private LocalDate created;

  @JsonView(View.Summary.class)
  private String title;

  @JsonView(View.Summary.class)
  private User author;

  private List<User> recipients;

  private String body;
}

在控制器中

@RestController
public class MessageController {

  @Autowired
  private MessageService messageService;

  @JsonView(View.Summary.class)
  @RequestMapping("/")
  public List<Message> getAllMessages() {
    return messageService.getAll();
  }

  @RequestMapping("/{id}")
  public Message getMessage(@PathVariable Long id) {
    return messageService.get(id);
  }
}

PS:没有指向http://fasterxml.com/ 的链接,因为它目前已关闭。

【讨论】:

  • 很高兴听到我能提供帮助。不要忘记将答案标记为已接受,以便其他人知道问题已解决;)
猜你喜欢
  • 1970-01-01
  • 2018-10-21
  • 2019-07-24
  • 2013-03-24
  • 2019-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多