我@JsonTypeInfo
用来指示杰克逊在@class
属性中查找具体类型信息。但是,有时我不想指定@class
,特别是当可以根据上下文推断子类型时。 最好的方法是什么?
这是 JSON 的示例:
{
"owner": {"name":"Dave"},
"residents":[
{"@class":"jacksonquestion.Dog","breed":"Greyhound"},
{"@class":"jacksonquestion.Human","name":"Cheryl"},
{"@class":"jacksonquestion.Human","name":"Timothy"}
]
}
我正在尝试将它们反序列化为这些类(全部在jacksonquestion.*
):
public class Household {
private Human owner;
private List<Animal> residents;
public Human getOwner() { return owner; }
public void setOwner(Human owner) { this.owner = owner; }
public List<Animal> getResidents() { return residents; }
public void setResidents(List<Animal> residents) { this.residents = residents; }
}
public class Animal {}
public class Dog extends Animal {
private String breed;
public String getBreed() { return breed; }
public void setBreed(String breed) { this.breed = breed; }
}
public class Human extends Animal {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
使用此配置:
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
private static class AnimalMixin {
}
//...
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.getDeserializationConfig().addMixInAnnotations(Animal.class, AnimalMixin.class);
Household household = objectMapper.readValue(json, Household.class);
System.out.println(household);
如您所见,所有者被声明为人类,而不是动物,因此我希望能够省略@class
并让杰克逊像往常一样推断类型。
当我运行这个时,我得到
org.codehaus.jackson.map.JsonMappingException: Unexpected token (END_OBJECT),
expected FIELD_NAME: missing property '@class' that is to contain type id (for class jacksonquestion.Human)
由于“所有者”没有指定@class
.
有任何想法吗?我最初的一个想法是使用@JsonTypeInfo
属性而不是类型。 但是,这不能用于注释列表的元素类型。 (不正确,见答案)