如何用Jackson 2.13.3将含对象引用的数据结构序列化为指定JSON
解决Jackson序列化对象引用时仅在顶层列表完整输出的问题
要实现所有Element对象仅在Container的allElements列表中完整序列化,其余关联位置仅输出ID,需要在Element类的引用字段上添加@JsonIdentityReference(alwaysAsId = true)注解,配合已有的@JsonIdentityInfo使用。
修改后的Element类代码
import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.JsonIdentityReference; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import java.util.List; @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") class Element { Element(String id) {this.id = id;} private String id; // 强制仅输出ID @JsonIdentityReference(alwaysAsId = true) private Element successor; @JsonIdentityReference(alwaysAsId = true) private Element predecessor; @JsonIdentityReference(alwaysAsId = true) private List<Element> upperNeighbours; @JsonIdentityReference(alwaysAsId = true) private List<Element> lowerNeighbours; // getter和setter方法保持不变 public String getId() {return id;} public void setId(String id) {this.id = id;} public Element getSuccessor() {return successor;} public void setSuccessor(Element successor) {this.successor = successor;} public Element getPredecessor() {return predecessor;} public void setPredecessor(Element predecessor) {this.predecessor = predecessor;} public List<Element> getUpperNeighbours() {return upperNeighbours;} public void setUpperNeighbours(List<Element> upperNeighbours) {this.upperNeighbours = upperNeighbours;} public List<Element> getLowerNeighbours() {return lowerNeighbours;} public void setLowerNeighbours(List<Element> lowerNeighbours) {this.lowerNeighbours = lowerNeighbours;} }
原理说明
@JsonIdentityInfo用于指定对象的ID生成规则,Jackson会通过id属性识别不同的Element实例。@JsonIdentityReference(alwaysAsId = true)强制所有对Element类型的引用(包括单个对象和列表中的对象)仅输出ID值,不会序列化对象的完整结构。- 只有当
Element作为allElements列表的直接元素时,Jackson才会完整序列化其所有属性,因为此时没有被@JsonIdentityReference的规则覆盖(该注解仅作用于引用字段)。
验证输出
修改后重新运行代码,输出的JSON将完全符合预期:所有Element的完整结构仅出现在allElements列表中,关联字段均以ID字符串形式展示。
内容的提问来源于stack exchange,提问作者heinrich
相关产品推荐
相关产品推荐

