我试图使用mixings序列化一个集合,但是Jackson不会保存类型信息。下面是一个基本测试,说明了发生的情况:
public class CollectionSerializationTest {
interface Common extends Serializable {
}
class A implements Common {
private static final long serialVersionUID = 1L;
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({ @JsonSubTypes.Type(value = A.class, name = "CODE") })
class AMixIn {
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({ @JsonSubTypes.Type(value = B.class, name = "CODE") })
class BMixIn {
}
class B implements Common {
private static final long serialVersionUID = 1L;
}
@Test
public void test() throws JsonGenerationException, JsonMappingException,
IOException {
ObjectMapper om = new ObjectMapper();
List<Common> list = new ArrayList<Common>();
A a = new A();
B b = new B();
list.add(a);
list.add(b);
om.getSerializationConfig().addMixInAnnotations(A.class, AMixIn.class);
om.getSerializationConfig().addMixInAnnotations(B.class, BMixIn.class);
System.out.println(om.writeValueAsString(list)); // Outputs [{},{}]
System.out.println(om.writeValueAsString(a));// Outputs {"type":"CODE"}
}
}
我该如何在第一个输出中实现
[{"type":"CODE"},{"type":"CODE"}]
的输出?