Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jackson why do I need JsonTypeName annotation on subclasses

At this link

I'm trying to understand why do I (may) need @JsonTypeName on subclasses (like all 'internet; sujests to put) if it works without it ?

@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")
}
like image 801
ses Avatar asked Nov 29 '15 02:11

ses


1 Answers

You don't need them.

The documentation of @JsonSubTypes.Type explains

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.

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
like image 146
zapl Avatar answered Oct 28 '22 07:10

zapl