【问题标题】:How to get mapping of array of subclasses in @RestController如何在@RestController 中获取子类数组的映射
【发布时间】:2019-10-03 22:13:58
【问题描述】:

我尝试在 SpringBoot 应用程序中为 RestController 实现端点。我希望我会收到这样的 POST 请求:

    {
      order: [
        {
         name: "Product1",
         type: "Fresh",
         expiryPeriod: "10"
        },
        {
         name: "Product2",
         type: "Frozen",
         manufacturingDate: "2017-03-08",
         storageTemp: "-40"
        }
      ]
    }

因此,我有抽象类 Product 和 2 个子类:FreshProduct 和 FrozenProduct。 问题是:如何通过@ResponseBody 获取List<Product>

【问题讨论】:

标签: java spring spring-boot


【解决方案1】:

像这样在你的抽象类中设置类型:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
        @JsonSubTypes.Type(value = FreshProduct.class, name = "fresh"),
        @JsonSubTypes.Type(value = FrozenProduct.class, name = "frozen")}
)
@Data
static abstract class AbstractProduct {
    String name;
    String type;
}

并在您的子类中设置类型名称,如下所示:

@JsonTypeName("fresh")
static class FreshProduct extends AbstractProduct {

}

@JsonTypeName("frozen")
static class FrozenProduct extends AbstractProduct {

}

关于 jackson-annotations 的更多信息:https://www.baeldung.com/jackson-annotations

【讨论】:

  • 拜托了!明确注解@Data是什么,来自什么包,是为了什么?
  • 非常感谢。没有@Data,我得到了正确的结果!
  • 这是一个用于 getter/setter 生成的 lombok 注释。更多信息:projectlombok.org/features/Data
  • 我在所有对象中都有字段“type”等于 null。你知道这个字段可以保持原始值吗?
  • @MichaelZal 尝试从 AbstractProduct 中删除字段“类型”。在我的示例中,Jackson 将此字段两次包含到 json 中。
猜你喜欢
  • 2019-07-26
  • 1970-01-01
  • 2022-11-30
  • 1970-01-01
  • 2020-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-20
相关资源
最近更新 更多