我有一个类,比如:
@Setter
@Getter
public class Parent {
private String name;
private String lastName;
private String address;
@Setter(AccessLevel.PRIVATE)
@JsonBackReference
private Child child;
public Parent() {
this.child = new Child();
child.setParent(this);
}
}
和一个处于复合关系中的孩子,比如:
@Setter
@Getter
public class Child {
private String nameChild;
private String lastNameChild;
@JsonManagedReference
private Parent parent;
}
我想要什么:
导入com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
public class Example {
@Test
public void Test() throws JsonProcessingException {
Parent parent = new Parent();
parent.setAddress("Address");
parent.setLastName("LastName");
parent.setName("Name");
parent.getChild().setNameChild("ChildName");
parent.getChild().setLastNameChild("ChildLastName");
Parent referenceToParent = parent.getChild().getParent();
ObjectMapper objMapper = new ObjectMapper();
String json = objMapper.writeValueAsString(referenceToParent);
Parent m = objMapper.readValue(json, Parent.class);
}
}
我想在referenceToParent中获得复合关系中的子对象对父对象的引用。
- 如何构造对象
- 我该如何处理Child->反序列化的父字段
反序列化的结果Notice子元素不存在,这不是预期的行为:
{"name":"Name","lastName":"LastName","address":"Address"}
您可以覆盖生成的setChild
和setParent
的Setter方法,如下面的
// Parent class
public void setChild(Child child) {
this.child = child;
if (child.getParent() == null) { // Prevent StackOverflowException
child.setParent(this);
}
}
//Child class
public void setParent(Parent parent) {
this.parent = parent;
if (parent.getChild() == null) { // Prevent StackOverflowException
parent.setChild(this);
}
}
@Test
public void test() {
Parent parent = new Parent();
parent.setAddress("Address");
parent.setLastName("LastName");
parent.setName("Name");
Child child = new Child();
child.setNameChild("ChildName");
child.setLastNameChild("ChildLastName");
parent.setChild(child);
assertNotNull(parent.getChild().getParent());
}
您呼叫parent.getChild().setLastNameChild("ChildLastName");
的问题是此时没有孩子。因此,要么在Parent
中的构造函数中创建一个始终为Child
的对象,要么像我一样传递Child
对象。
---编辑
如果我理解你的意见正确,你可以选择以下方式来防止手动安装。
@Setter
@Getter
public class Parent implements Serializable {
private String name;
private String lastName;
private String address;
@Setter(AccessLevel.PRIVATE)
private Child child;
public Parent() {
this.child = new Child();
child.setParent(this);
}
}
@Test
public void test() {
Parent parent = new Parent();
parent.setAddress("Address");
parent.setLastName("LastName");
parent.setName("Name");
parent.getChild().setNameChild("ChildName");
parent.getChild().setLastNameChild("ChildLastName");
assertNotNull(parent.getChild().getParent());
}
私有setChild()
方法防止覆盖子级。如果你想手动设置子项,那么你必须将这两种方法结合起来。
公共setParent()
可能是关键的,因为可以覆盖相关的父级。