10

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")
}
Community
  • 1
  • 1
ses
  • 13,174
  • 31
  • 123
  • 226
  • 1
    Does it work without them? I.e. can you deserialize json with `"aType":"ModelB"` into the correct objects? There is lots of cargo cult programming, some may have been required once upon a time – zapl Nov 29 '15 at 02:37
  • yest.that works "to and from". i guess it may be needed. just want to know at wich case. i guess it may depends on JsonTypeInfo params other than Id.Name. – ses Nov 29 '15 at 02:46

1 Answers1

20

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
zapl
  • 63,179
  • 10
  • 123
  • 154