Spring 使用具体实现时REST端点中@JsonTypeInfo的影响
我想知道将Spring 使用具体实现时REST端点中@JsonTypeInfo的影响,spring,rest,kotlin,jackson,polymorphism,Spring,Rest,Kotlin,Jackson,Polymorphism,我想知道将@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS,include=JsonTypeInfo.As.PROPERTY,PROPERTY=“@CLASS”)添加到接口的效果如何 我的用例是,我有一个带有许多子类型的接口消息。我希望能够在一个端点中反序列化和序列化消息列表 我的班级: @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property =
@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS,include=JsonTypeInfo.As.PROPERTY,PROPERTY=“@CLASS”)
添加到接口的效果如何
我的用例是,我有一个带有许多子类型的接口消息。我希望能够在一个端点中反序列化和序列化消息列表
我的班级:
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
interface Message: Serializable
data class Message1(
val name: String,
val age: Int
)
data class Message2(
val name: String,
val nickName: String
)
以及相应的端点:
@RestController
class MessageController {
@GetMapping("/messages")
fun getEndpoints(): List<Message> {
return listOf(
Message1("Marco", 22),
Message2("Polo", "Poli")
)
}
}
为什么即使我使用的是一个具体的类,仍然需要
@class
?这是预期的行为还是我做错了什么 这是意料之中的,因为通过类接口继承,通过使用@JsonTypeInfo
注释类,您已经明确指示您的Jackson需要这些信息
@JsonTypeInfo
接受将使用的类型为Class
的参数defaultImpl
如果类型标识符不存在,或者无法映射到已注册的类型
您可以使用它将反序列化默认为一种消息类型,最好是在api中显式使用最广泛的消息类型。对于其他类型,您仍然需要包含Jackson的类信息。这是预期的,因为通过类接口继承,使用
@JsonTypeInfo
注释该类,您已经明确指示您的Jackson预期该信息
@JsonTypeInfo
接受将使用的类型为Class
的参数defaultImpl
如果类型标识符不存在,或者无法映射到已注册的类型
您可以使用它将反序列化默认为一种消息类型,最好是在api中显式使用最广泛的消息类型。对于其他类型,您仍然需要包含Jackson的课程信息。好的,谢谢,对于我来说仍然很奇怪,它需要一个具体类型的反序列化上的
@class
属性-我现在通过将列表
包装到DTO中,并仅将注释添加到包含messagesokay列表的DTO的属性中来解决它,对我来说仍然很奇怪的是,它在反序列化一个具体类型时需要@class
属性-我现在通过将列表
包装到DTO中,并且只向包含消息列表的DTO的属性添加注释来解决这个问题
@RestController
class MessageController {
@PostMapping("/add1")
fun add(@RequestBody content: Message1) {
// do something
}
}
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Missing type id when trying to resolve subtype of [simple type, class com.tractive.tap.message.request.RequestDataDTO]: missing type id property '@class'; nested exception is com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Missing type id when trying to resolve subtype of [simple type, class com.tractive.tap.message.request.RequestDataDTO]: missing type id property '@class'
at [Source: (PushbackInputStream); line: 1, column: 51]