gpt4 book ai didi

java - 序列化多态对象列表时未设置类型 ID 字段

转载 作者:行者123 更新时间:2023-11-30 08:40:20 26 4
gpt4 key购买 nike

考虑我编写的这段代码,以玩转 Jackson 对多态序列化/反序列化的支持 ( http://wiki.fasterxml.com/JacksonPolymorphicDeserialization ) -

public class Main {

@JsonTypeInfo(
use=JsonTypeInfo.Id.NAME,
include=JsonTypeInfo.As.PROPERTY,
property="type")
@JsonSubTypes({
@JsonSubTypes.Type(name = "dog", value = Dog.class),
@JsonSubTypes.Type(name = "cat", value = Cat.class)
})
public abstract static class Animal {
public String name;
}

public static class Dog extends Animal {
public int barkLevel;
}

public static class Cat extends Animal {
public int meowLevel;
}

public static void main(String[] args) throws Exception {

String marshalled = "" +
"[\n" +
" {\n" +
" \"name\" : \"cookie\",\n" +
" \"type\" : \"dog\",\n" +
" \"barkLevel\" : 5\n" +
" },\n" +
" {\n" +
" \"name\" : \"misty\",\n" +
" \"type\" : \"cat\",\n" +
" \"meowLevel\" : 3\n" +
" }\n" +
"]\n";

ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);

List<Animal> unmarshalledList = mapper.readValue(
marshalled,
new TypeReference<List<Animal>>() {}
);

Animal[] unmarshalledArray = mapper.readValue(
marshalled,
new TypeReference<Animal[]>() {}
);

for (Animal animal : unmarshalledList) {
System.out.println(animal.getClass().getSimpleName());
}
System.out.println(
mapper.writeValueAsString(
unmarshalledList
) + "\n"
);

for (Animal animal : unmarshalledArray) {
System.out.println(animal.getClass().getSimpleName());
}
System.out.println(
mapper.writeValueAsString(
unmarshalledArray
)
);
}
}

它产生以下输出 -

Dog
Cat
[ {
"name" : "cookie",
"barkLevel" : 5
}, {
"name" : "misty",
"meowLevel" : 3
} ]

Dog
Cat
[ {
"type" : "dog",
"name" : "cookie",
"barkLevel" : 5
}, {
"type" : "cat",
"name" : "misty",
"meowLevel" : 3
} ]

我的问题是 - 当我序列化 List 时,生成的 json 中不包含任何类型字段。但是,如果我改用 Animal[],则生成的 json 中会包含一个类型字段。在这两种情况下,反序列化工作正常,即。使用了正确的子类。有人可以解释这种行为的原因吗?

最佳答案

要使用多态序列化序列化通用集合,您需要执行以下操作:

mapper.writerFor(new TypeReference<List<Animal>>() {}).writeValueAsString(unmarshalledList));

参见 this GitHub issue有关为什么需要这样做的更多详细信息。

关于java - 序列化多态对象列表时未设置类型 ID 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35714346/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com