我正在尝试使用混音序列化一个集合,但杰克逊不会保存类型信息。这是一个基本的测试,说明了会发生什么:
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"}]
?
答案 0 :(得分:1)
我不确定这是否是最简单的解决方案,但我认为你可以这样做:
扩展ArrayList
的新Java类:
@JsonSerialize(using = JacksonListSerializer.class)
class JacksonList<E> extends ArrayList<E> {
private static final long serialVersionUID = 1L;
}
上述类的序列化程序:
class JacksonListSerializer extends JsonSerializer<JacksonList<?>> {
@Override
public void serialize(JacksonList<?> list, JsonGenerator generator, SerializerProvider provider)
throws IOException, JsonProcessingException {
generator.writeStartArray();
if (list != null) {
for (Object item : list) {
generator.writeObject(item);
}
}
generator.writeEndArray();
}
}
现在,您可以在示例中使用此列表:
public static void main(String[] args) throws IOException {
ObjectMapper om = new ObjectMapper();
List<Common> list = new JacksonList<Common>();
list.add(new A());
list.add(new B());
om.addMixInAnnotations(A.class, AMixIn.class);
om.addMixInAnnotations(B.class, BMixIn.class);
System.out.println(om.writeValueAsString(list));
System.out.println(om.writeValueAsString(new A()));
}
以上示例打印:
[{"type":"CODE"},{"type":"CODE"}]
{"type":"CODE"}