杰克逊:自定义集合序列化到JSON [英] Jackson : custom collection serialization to JSON
问题描述
我正在尝试json序列化一个MyRootClass类,其属性是第二个类MyClass元素的集合:
I am trying to json-serialize a class MyRootClass with a property that is a collection of elements of a second class MyClass:
public class MyRootClass {
private List<MyInterface> list = new ArrayList<MyInterface>();
// getter / setter
}
public class MyClass implements MyInterface {
private String value = "test";
// getter / setter
}
以下代码:
MyRootClass root = new MyRootClass();
root.getList().add(new MyClass());
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(System.out, root);
生成此JSON输出:
{"list": [ {"value":"test"} ] }
而不是我需要的,集合中的每个对象都用一个名字序列化:
instead of what I need, every object in the collection serialized with a name:
{"list": [ {"myclass": {"value":"test"}} ] }
有没有办法使用杰克逊实现它?我想过编写一个自定义序列化程序,但是我找不到任何与对象集合相关的内容。
Is there any way to achieve it using Jackson? I thought about writing a custom serializer, but I've not found anything related to a collection of objects.
推荐答案
这取决于你想用名字实现什么目标;但是,如果你想在这里包含'myclass'是类型信息(或者可以表现得好像使用它;如果你不使用Jackson反序列化它并不重要),可以这样做。
It depends on what exactly you want to achieve with name; but yes, this can be done if you want to include 'myclass' here is type information (or can act as if it was used; if you do not use Jackson to deserialize it does not really matter).
如果是这样,你会注释MyInterface:
If so, you would annotate MyInterface:
@JsonTypeInfo(use=Id.NAME, include=As.WRAPPER_OBJECT)
和MyClass with:
and MyClass with:
@JsonTypeName("myclass")
(如果你没有定义它,默认名称将是类的非限定名称)
(if you don't define that, default name would be unqualified name of the class)
@JsonTypeInfo
上面定义将使用该类型名称(而不是Java类名称或自定义方法),并使用包装器对象完成包含(替代方法是包装器数组和as-property)
@JsonTypeInfo
above defines that type name is to be used (instead of Java class name, or custom method), and inclusion is done by using a wrapper object (alternatives are wrapper array and as-property)
所以你应该看到预期的输出。
So you should then see expected output.
这篇关于杰克逊:自定义集合序列化到JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!