Using scala-reflect to work out the classes that implement the sealed trait (or abstract class).
case class Car(make: String, color: Color)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
sealed trait Color
case object Red extends Color
case object Green extends Color
case object Blue extends Color
val mapper = JsonMapper.builder()
.addModule(DefaultScalaModule)
.addModule(ScalaObjectDeserializerModule) //this non-default module prevents duplicate scala objects being created
.addModule(ScalaReflectAnnotationIntrospectorModule)
.build()
val car = Car("Samand", Red)
val json = mapper.writeValueAsString(car)
val car2 = mapper.readValue(json, classOf[Car])
car2.color shouldEqual car.color
car2.make shouldEqual car.make
Unfortunately, you still need to add a JsonTypeInfo to the trait (or abstract class) but you don't need to list out the classes that implement it. ScalaReflectAnnotationIntrospectorModule is the module that enables this.
Using scala-reflect to work out the classes that implement the sealed trait (or abstract class).
Unfortunately, you still need to add a JsonTypeInfo to the trait (or abstract class) but you don't need to list out the classes that implement it. ScalaReflectAnnotationIntrospectorModule is the module that enables this.