java - jackson 为什么我需要在子类上进行 JsonTypeName 注释

标签 java json scala jackson jackson-module-scala

this link

我正在尝试理解为什么我(可能)需要 @JsonTypeName在子类上(像所有 'internet; 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")
}

最佳答案

你不需要它们。

documentation @JsonSubTypes.Type 解释

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

关于java - jackson 为什么我需要在子类上进行 JsonTypeName 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33978725/

相关文章:

java 查找字符串是否包含另外2个字符串

javascript - 如何将Javascript连接到Python以两种方式共享JSON格式的数据?

scala - 使用反射进行 JSON 反序列化

sql - Scala with spark - "javax.servlet.ServletRegistration"的签名者信息与同一包中其他类的签名者信息不匹配

java - Sun Directory Server 无法连接 ldap 服务器

java - 在 Java 中向已初始化的对象数组添加值?

ios - 需要从open api获取国家名称

javascript - 展平嵌套 json 对象

scala - 为什么在 scala 中不能覆盖可变变量?

java - 添加配置单元 jdbc 依赖项会破坏 Glassfish 部署