SpringBoot:请求带有继承的主体 [英] SpringBoot: Request body with inheritance

查看:66
本文介绍了SpringBoot:请求带有继承的主体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程

public class Car {
     private String make; 
     private String model; 
     
     private TransmissionType transmissionType; // Manual/Automatic
     private Transmission transmission; 
}

public class Transmission {
}

public class AutomaticTransmission {
     public Technology technology; // DCT/CVT/AMT
}

public class ManualTransmission {
     public int numGears; 
}

在这个例子中,当有效载荷传递可能是

In this example, when the payload passed could be

{
    "make": "Toyota", 
    "model": "Iris", 
    "transmissionType": "Automatic", 
    "transmission" {
         "technology": "DCT"
    }
}

也可以

{
    "make": "Merc", 
    "model": "C", 
    "transmissionType": "Manual", 
    "transmission" {
         "numGears": 5
    }
}

当它作为主体传递给控制器​​时,它应该能够创建相应的类.我如何实现这一目标.

When this is passed to controller as body, it should be able to create respective class. How do I achieve this.

我尝试使用 JsonTypeInfoJsonSubTypes,如 this answer 但它需要我在 Transmission 类中移动 transmissionType,这对我来说不是这种情况.

I tried using JsonTypeInfo and JsonSubTypes as shown in this answer but it necessitates me to move transmissionType within Transmission class, which is not the case for me.

推荐答案

您正在寻找 @JsonTypeInfo(include = As.EXTERNAL_PROPERTY) 传输传输.这告诉 Jackson 在包含对象中查找定义类型的属性.

You're looking for @JsonTypeInfo(include = As.EXTERNAL_PROPERTY) Transmission transmission. This tells Jackson to look for the property that defines the type in the containing object.

也就是说,如果您有机会更改 JSON 形状,则应避免使用外部标记类型";像这样,将type属性放入对象中.

That said, if you have any opportunity of changing your JSON shape, you should avoid "externally tagged types" like this and put the type property into the object.

这篇关于SpringBoot:请求带有继承的主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆