Kotlin 在 Jackson 中密封了 class 子类型
Kotlin sealed class subtyping in Jackson
我关注类:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes(
JsonSubTypes.Type(value = Speech::class, name = "Speech"),
JsonSubTypes.Type(value = Audio::class, name = "Audio"),
)
sealed class AudioItem
data class Speech(val type: String = "Speech", val contentType: String = "SSML", val content: String) : AudioItem()
data class Audio(val type: String = "Audio", val source: String) : AudioItem()
当我尝试转换泛型时 ArrayList
:
到AudioItem
val audio: List<AudioItem> = ObjectMapper().findAndRegisterModules().convertValue(a)
我得到:
Cannot construct instance of AudioItem
(no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
它应该在您使用 sealed class AudioItem()
时起作用(注意“()”)。 IntelliJ 提示我们可以删除“()”,但如果我这样做,那么我在“结构”选项卡中看不到任何构造函数。
此外,您不需要像 val type: String = "Speech"
中那样显式设置类型。 @JsonSubTypes
会为你做到这一点。
我关注类:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes(
JsonSubTypes.Type(value = Speech::class, name = "Speech"),
JsonSubTypes.Type(value = Audio::class, name = "Audio"),
)
sealed class AudioItem
data class Speech(val type: String = "Speech", val contentType: String = "SSML", val content: String) : AudioItem()
data class Audio(val type: String = "Audio", val source: String) : AudioItem()
当我尝试转换泛型时 ArrayList
:
到AudioItem
val audio: List<AudioItem> = ObjectMapper().findAndRegisterModules().convertValue(a)
我得到:
Cannot construct instance of
AudioItem
(no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
它应该在您使用 sealed class AudioItem()
时起作用(注意“()”)。 IntelliJ 提示我们可以删除“()”,但如果我这样做,那么我在“结构”选项卡中看不到任何构造函数。
此外,您不需要像 val type: String = "Speech"
中那样显式设置类型。 @JsonSubTypes
会为你做到这一点。