我有以下示例类:
class Zoo {
public Collection<? extends Animal> animals;
}
序列化时,我试图通过以下方式尽可能多地序列化类型信息:
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
我得到以下 JSON:
[
"com.bp.samples.json.generics.Zoo",
{
"animals": [
"java.util.ArrayList",
[
[
"com.bp.samples.json.generics.Bird",
{
"name": "bird-1",
"wingSpan": "6 feets",
"preferredFood": "food-1"
}
],
[
"com.bp.samples.json.generics.Cat",
{
"name": "cat-1",
"favoriteToy": "toy-1"
}
],
[
"com.bp.samples.json.generics.Dog",
{
"name": "dog-1",
"breed": "bread-1",
"leashColor": "black"
}
]
]
]
}
]
当涉及到反序列化时,尝试做:
mapper.readValue(new File("./DataFiles/Zoo-2.json"), Zoo.class);
导致以下异常:
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException:
Can not deserialize instance of com.bp.samples.json.generics.Zoo out of START_ARRAY toke
并尝试做:
mapper.readValue(new File("./DataFiles/Zoo-2.json"),
new TypeReference<Collection<? extends Animal>>() {});
结果是:
Can not construct instance of com.bp.samples.json.generics.Animal,
problem: abstract types either need to be mapped to concrete types, have custom
deserializer, or be instantiated with additional type information
at [Source: ./DataFiles/Zoo-2.json; line: 2, column: 5]
当然,编写自定义反序列化程序可以解决问题,但是如果没有自定义反序列化程序,是否可以进行反序列化?
谢谢,贝扎德