JSON嵌套类数据绑定 [英] JSON nest class data binding
问题描述
{type:cat,animal:{name:cat}}
Animal是抽象类
。猫和狗是子类
。
Animal is an abstract class
. Cat and Dog are subclass
.
现在我正在尝试将json转换为java对象
并希望使用type来获取子类。
Now I am trying to convert json to java object
and want to use "type" to get the subclass.
但是类型字段不在列中。
But the type field is out of animal the column.
提前致谢:)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property= "type")
@JsonSubTypes({ @Type(value = Cat.class, name = "cat"),
@Type(value = Dog.class, name = "dog") })
abstract class Animal {
public String name;
}
class Cat extends Animal {
public String name;
}
class Dog extends Animal {
public String name;
}
问题是类型是动物{}。
the question is the type is out of animal{}.
如果类型在动物{}中,代码将起作用。但它不是:
if the type is in the animal{} the code will works. but it isn`t ):
推荐答案
这是可能的,但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\" }}"
这篇关于JSON嵌套类数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!