【问题标题】:Spring Boot Jackson Databind - Configure InheritanceSpring Boot Jackson Databind - 配置继承
【发布时间】:2018-11-04 07:55:11
【问题描述】:

假设我有一个基类A

public class A {
    public String a;
}

还有两个子类BC

public class B extends A {
    public String b;
}

public class C extends A {
    public String c;
}

A 类的包装器:

public class Wrapper {
    public A a;
}

我有接收客户端请求作为包装对象的 Rest 控制器:

@RestController
public class SomeController {

    public void foo(@RequestBody Wrapper wrapper) {}

}

问题在于 Jackson 将包装器字段强制转换为基类 A

如何配置它以接收正确的类型?

【问题讨论】:

标签: java spring-boot jackson jackson-databind


【解决方案1】:

用类型信息注释你的基类A,告诉Jackson如何决定给定的json对象是否应该反序列化为B.javaC.java

例如:通过下面的代码,我们告诉杰克逊 A.class 的 json 对象将包含一个带有键 type 的属性,其值可以是“b”或“c”。如果值为“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 {
}

以下是您应该使用的 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
   }
}

【讨论】:

  • 我做对了,但重要的是不能实例化基类。基类应为abstractinterface
猜你喜欢
  • 1970-01-01
  • 2017-08-28
  • 2018-06-28
  • 2019-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-25
  • 2019-06-07
相关资源
最近更新 更多