如果您只想避免遞歸,則可以使用@JsonIdentityInfo。它會爲每個對象生成id,如果重複,則用它的id替換重複的對象。
下面是一個簡單的父/子例如:
@JsonIdentityInfo(generator=IntSequenceGenerator.class)
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
public class Parent {
private List<Child> children=new ArrayList<>();
private String name="parent";
public Parent() {
super();
children.add(new Child(this,"foo"));
children.add(new Child(this,"bar"));
}
public List<Child> getChildren() {
return children;
}
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
public class Child {
private Parent parent;
private String pseudo="toto";
public Child(Parent parent, String pseudo) {
super();
this.parent = parent;
this.pseudo = pseudo;
}
}
public class SOJson {
public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
Parent object=new Parent();
String json1 = objectMapper.writeValueAsString(object);
System.out.println("write parent: "+json1);
String json2 = objectMapper.writeValueAsString(object.getChildren().get(0));
System.out.println("write child: "+json2);
}
}
結果:
write parent: {"@id":1,"children":[{"parent":1,"pseudo":"foo"},{"parent":1,"pseudo":"bar"}],"name":"parent"}
write child: {"parent":{"@id":1,"children":[{"parent":1,"pseudo":"foo"},{"parent":1,"pseudo":"bar"}],"name":"parent"},"pseudo":"foo"}
你看,有孩子和父母之間的遞歸,如果去掉@ JsonIdentityInfo你將有一個計算器。
當然,你需要的地方停止你的遞歸,否則你將轉儲數據庫!二者必選其一@jsonIgnore到某處停止你的遞歸或Hibernate4Module上卸載延遲屬性停止遞歸。 (我更喜歡使用兩者)