微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – jackson为什么我需要在子类上使用JsonTypeName注释

this link

我试图理解为什么我(可能)在子类上需要@JsonTypeName(比如所有’互联网; sujests to put)如果没有它就可以工作?

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "aType")
@JsonSubTypes(Array(
  new Type(value = classOf[ModelA], name = "ModelA"),
  new Type(value = classOf[ModelB], name = "ModelB")
))
class BaseModel(val modelName:String)

//@JsonTypeName("SomeModel")  // Commented. Do I need this?
class ModelA(val a:String, val b:String, val c:String, commonData:String)  extends BaseModel(commonData) {
  def this() = this("default", "default", "default" ,"default")
}
//@JsonTypeName("SomeModel") // Commented. Do I need this?
class ModelB(val a:String, val b:String, val c:String, commonData:String)  extends BaseModel(commonData) {
  def this() = this("default", "default", "default" ,"default")
}

解决方法:

你不需要它们.

@JsonSubTypes.Type的documentation解释

DeFinition of a subtype, along with optional name. If name is missing, class of the type will be checked for JsonTypeName annotation; and if that is also missing or empty, a default name will be constructed by type id mechanism. Default name is usually based on class name.

你应该有

@JsonSubTypes(Array(
  new Type(value = classOf[ModelA], name = "ModelA")

... 

class ModelA

要么

@JsonSubTypes(Array(
  new Type(value = classOf[ModelA])

... 

@JsonTypeName("ModelA")
class ModelA

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐