更新时间:2023-01-17 08:12:53
这是可能的,但JSON中的类型应该类似于类型:com.test.Cat
(完全限定名称)
抽象类
It's possible, but type in JSON should looks like "type":"com.test.Cat"
(fully qualified name)
Abstract class
@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="type")
public abstract class AAnimal
{
}
子类
public class Cat extends AAnimal
{
public String name;
}
public class Dog extends AAnimal
{
public String name;
}
现在,对于json
"{ \"type\":\"com.test.Dog\", \"name\":\"gav-gav\" }"
它将是 Dog
instance
和
it will be Dog
instance
and for
"{ \"type\":\"com.test.Cat\", \"name\":\"mew-mew\" }"
它将是 Cat
实例
编辑
在这种情况下使用 JsonTypeInfo.As.EXTERNAL_PROPERTY
。示例
public class Container
{
private String type;
private AAnimal animal;
public String getType()
{
return type;
}
public void setType(String type)
{
this.type = type;
}
public AAnimal getAnimal()
{
return animal;
}
@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.EXTERNAL_PROPERTY, property="type")
public void setAnimal(AAnimal animal)
{
this.animal = animal;
}
}
动物类
public abstract class AAnimal
{
public String name;
}
public class Cat extends AAnimal
{
}
public class Dog extends AAnimal
{
}
"{\"type\":\"com.test.Cat\", \"animal\" : {\"name\":\"cat\" }}"
效果很好。
PS。
另外您可以使用 use = JsonTypeInfo.Id.MINIMAL_CLASS
,在这种情况下,您只能使用部分完全限定名称
EDIT2
it works well.
PS.
Also you can use use=JsonTypeInfo.Id.MINIMAL_CLASS
, in this case you can use only part of fully qualified name
EDIT2
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.EXTERNAL_PROPERTY, property="type")
@JsonSubTypes({ @Type(value = Cat.class, name = "cat"), @Type(value = Dog.class, name = "dog") })
public void setAnimal(AAnimal animal)
{
this.animal = animal;
}
适用于
"{\"type\":\"cat\", \"animal\" : {\"name\":\"cat\" }}"