一尘不染

使用杰克逊将双向JPA实体序列化为JSON

json

我正在使用Jackson将JPA模型序列化为JSON。

我有以下课程:

import com.fasterxml.jackson.annotation.*;
import javax.persistence.*;
import java.util.Set;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class)
@Entity
public class Parent {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String name;

  @JsonManagedReference
  @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
  private Set<Child> children;

  //Getters and setters
}

import com.fasterxml.jackson.annotation.*;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)
@Entity
public class Child {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String name;

  @JsonBackReference
  @ManyToOne
  @JoinColumn(name = "parentId")
  private Parent parent;

  //Getters and setters
}

我正在使用POJO映射从模型序列化为JSON。当我序列化Parent对象时,我得到以下JSON:

{
  "id": 1,
  "name": "John Doe",
  "children": [
    {
      "id": 1,
      "name": "child1"
    },{
      "id": 2,
      "name": "child2"
    }
  ]
}

但是当我序列化一个Child时,我得到以下JSON:

{
  "id": 1,
  "name": "child1"
}

缺少对父级的引用。有办法解决吗?


阅读 295

收藏
2020-07-27

共1个答案

一尘不染

我认为您必须在@JsonIdentityInfo和@ JsonBackReference / @ JsonManagedReference之间进行选择。

我会在您的实体上使用@JsonIdentityInfo(generator =
ObjectIdGenerators.PropertyGenerator.class,property =“ id”),删除@
JsonBackReference / @ JsonManagedReference对。

并在要排除的字段上添加@JsonIgnore。

2020-07-27