使用 jackson 将双向 JPA 实体序列化为 JSON [英] Serialize bi-directional JPA entities to JSON with jackson
问题描述
我正在使用 Jackson 将我的 JPA 模型序列化为 JSON.
I'm using Jackson to serialize my JPA model into 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.当我序列化父对象时,我得到以下 JSON:
I'm using the POJO mapping to serialize from model to JSON. When I serialize a Parent object I get the following JSON:
{
"id": 1,
"name": "John Doe",
"children": [
{
"id": 1,
"name": "child1"
},{
"id": 2,
"name": "child2"
}
]
}
但是当我序列化一个 Child 时,我得到以下 JSON:
But when I serialize a Child I get the following JSON:
{
"id": 1,
"name": "child1"
}
缺少对父项的引用.有没有办法解决这个问题?
The reference to the parent is missing. Is there a way to solve this?
推荐答案
我认为你必须在 @JsonIdentityInfo
和 @JsonBackReference
/@ 之间做出选择JsonManagedReference
.
I think you have to choose between the @JsonIdentityInfo
and the @JsonBackReference
/ @JsonManagedReference
.
我会在你的实体上使用:@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property=id")
,删除@JsonBackReference
/@JsonManagedReference
对.
I would go with : @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property="id")
on your entities, removes @JsonBackReference
/ @JsonManagedReference
pairs.
并在要排除的字段上添加 @JsonIgnore
.
And add @JsonIgnore
on the fields you want to exclude.
这篇关于使用 jackson 将双向 JPA 实体序列化为 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!