[英]Spring Boot Jackson Databind - Configure Inheritance
Suppose I have a base class A
: 假设我有一个基类A
:
public class A {
public String a;
}
And two child classes B
and C
: 还有两个子类B
和C
:
public class B extends A {
public String b;
}
public class C extends A {
public String c;
}
And wrapper of A
class: 和A
类的包装:
public class Wrapper {
public A a;
}
And I have Rest controller that receives client requests as wrapper object: 我有Rest控制器,它接收客户端请求作为包装对象:
@RestController
public class SomeController {
public void foo(@RequestBody Wrapper wrapper) {}
}
The problem is that Jackson casts wrapper field to base class A
. 问题是杰克逊将包装器字段转换为基类A
How can I configure it to recieve correct type? 如何配置它以接收正确的类型?
Annotate your base class A
with type information that tells Jackson how to decide whether a given json object should be deserialized to B.java
or C.java
. 用类型信息注释基类A
,该信息告诉Jackson如何决定将给定的json对象反序列化为B.java
或C.java
。
Ex: With the below code, we are telling jackson that json object for A.class will contain a property with key type
whose value can be either "b" or "c". 例如:使用下面的代码,我们告诉杰克逊,A.class的json对象将包含一个键type
为属性的属性,其值可以是“ b”或“ c”。 If the value is "b", deserialize the object to B.class
, else deserialize it to C.class
如果值为“ b”,则将该对象反序列化为B.class
,否则将其反序列C.class
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
@Type(value = B.class, name = "b"),
@Type(value = B.class, name= "c")
})
class A {
}
Following is the json that you should be using. 以下是您应该使用的json。
{
"a" : { // This will be deserialized to B.class
"type": "b",
// field of B.class
}
}
{
"a" : { // This will be deserialized to C.class
"type": "c",
// field of C.class
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.