它可以與傑克遜的Object Identity feature的幫助來完成:
藏品必須的值包裹在他們自己的類被註釋,使得傑克遜生成用於不同集合的對象ID:
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")
public class Values
{
public List<String> values = new ArrayList<>();
public Values() {}
public Values(String... values) {
this.values = Arrays.asList(values);
}
/**
* implement equals() and hashCode() so that instances can be put into Maps Sets and such
*/
@Override
public boolean equals(Object other) {
return other instanceof Values ? ((Values)other).values.equals(values) : false ;
}
@Override
public int hashCode() {
return values.hashCode();
}
}
以下類包裝ref
和fields
。串行次序被exlicitly限定爲使得傑克遜將生成對象ID爲MyClass的
new ObjectMapper().writeValue(System.out, new MyClass());
的refs
@JsonPropertyOrder({"refs", "fields"})
public class MyClass
{
public Set<Values> refs = new HashSet<>();
public Map<String, Values> fields = new HashMap<>();
public MyClass()
{
Values v1 = new Values("X", "Y", "Z");
Values v2 = new Values("1", "2", "3");
fields.put("A", v1);
fields.put("B", v2);
fields.put("C", v1);
fields.values().forEach(value -> refs.add(value));
}
}
系列化的內容產生
{"refs":[{"@id":1,"values":["1","2","3"]},{"@id":2,"values":["X","Y","Z"]}],"fields":{"A":2,"B":1,"C":2}}