2015-11-30 71 views
0

我正在與傑克遜解析,並想知道是否有任何方式在傑克遜創建這樣的JSON文件?JACKSON:對象標識符爲外部

"fields": { 
    "A" : { "ref" : 1}, 
    "B" : { "ref" : 2}, 
    "C" : { "ref" : 1} 
}, 
"refs" : [ 
    {"@id" : 1, "values" : ["X", "Y", "Z"] }, 
    {"@id" : 2, "values" : ["1", "2", "3] } 
] 

其中「A」將有參考「裁判」元素定義字符串數組

回答

1

它可以與傑克遜的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(); 
    } 
} 

以下類包裝reffields。串行次序被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}}