我必須在 Spring Boot Controller 方法中的 RequestBody 中傳遞 2 種不同型別的蘋果或橙色型別的物件。
public myResponse myMethod(@ApiParam(value = "myRequest", required = true) @RequestBody Object mulRequest) {
在上面的代碼片段中,型別為 Object 的 mulRequest 可以是 Class apple 或 Class orange。
我想按照我的要求遵循以下邏輯 -
if (mulRequest instanceof apple) {
// process logic...
} else if (mulRequest instanceof orange) {
// process...
}
但是我堅持如何根據傳遞的 RequestBody 轉換到相關的類物件,因為我不知道為 mulRequest 傳遞的是什么型別的物件,它可以是蘋果類或橙色類。apple 和 orange 類都實作了 Serializable 介面。
感謝任何解決此問題的建議或方法。
uj5u.com熱心網友回復:
您正在尋找的是什么@JsonTypeInfo,并@JsonSubTypes正在增加對反序列化polymorphizm支持杰克遜的注解。
為了讓 Jackson 了解它應該如何反序列化 JSON 物件,您可能需要在序列化物件時提供一些額外的屬性或添加類名 - 這取決于您將決定使用的反序列化策略。
您的 DTO 和控制器的示例實作可能如下所示:
@JsonTypeInfo(use = Id.NAME, include = As.PROPERTY, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = Apple.class, name = "apple"),
@JsonSubTypes.Type(value = Orange.class, name = "orange")
})
public abstract class Fruit implements Serializable { // basically you do not need this Serializable at all here
String someData;
//...
// note that we can but we do not need to define 'type' field!
// Jackson will handle it if it will appear in JSON
}
public class Orange extends Fruit {
//...
}
public class Apple extends Fruit {
//...
}
然后當你的 JSON 看起來像
{
"someData": "test",
"type": "orange"
}
你將提供以下控制器
public myResponse myMethod(@ApiParam(value = "myRequest", required = true) @RequestBody Fruit mulRequest) {
然后mulRequest可以測驗它是Apple還是Orange。當然你不能使用那里的Object類,因為你不能用 Jackson 注釋來注釋它,但是也許提供自定義反序列化器你將能夠實作它。但它會非常非常可疑
請閱讀以下文章以更好地理解這一點:
- Jackson 基于型別反序列化
- @JsonTypeInfo 和 @JsonSubTypes 在 jackson 中的用途是什么
- https://octoperf.com/blog/2018/02/01/polymorphism-with-jackson/
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/366406.html
下一篇:SpringSecurityAuthenticationManagerauthenticate()方法如何能夠檢查發送的用戶名和密碼是否正確?
