JACKSON:外部的对象标识符

时间:2015-11-30 10:31:19

标签: json serialization jackson

我正在使用杰克逊解析并想知道杰克逊是否有办法创建这样的JSON文档?

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

其中" A"将引用在" refs"中定义的字符串数组。元件

1 个答案:

答案 0 :(得分:1)

可以在杰克逊的Object Identity feature

的帮助下完成

值集合需要包装在他们自己的注释类中,以便Jackson为不同的集合生成对象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。序列化顺序是明确定义的,以便jackson将为refs

的内容生成对象ID
@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));
    }
}

MyClass的序列化

new ObjectMapper().writeValue(System.out, new MyClass());

生成

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