scala jackson 为什么我需要在子类上添加 JsonTypeName 注释
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33978725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hymanson why do I need JsonTypeName annotation on subclasses
提问by ses
At this link
在这个链接
I'm trying to understand whydo I (may) need @JsonTypeNameon subclasses (like all 'internet; sujests to put) if it works without it ?
我试图理解为什么我(可能)需要@JsonTypeName子类(如所有“互联网;要放置的对象”),如果没有它也能工作?
@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")
}
回答by zapl
You don't need them.
你不需要它们。
The documentationof @JsonSubTypes.Typeexplains
该文件的@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.
子类型的定义以及可选名称。如果缺少 name,将检查该类型的类是否有 JsonTypeName 注释;如果它也缺失或为空,则将通过类型 id 机制构造一个默认名称。默认名称通常基于类名。
You should have either
你应该有
@JsonSubTypes(Array(
new Type(value = classOf[ModelA], name = "ModelA")
...
class ModelA
or
或者
@JsonSubTypes(Array(
new Type(value = classOf[ModelA])
...
@JsonTypeName("ModelA")
class ModelA

