pjfanning / jackson-scala-reflect-extensions

Extension to jackson-module-scala that uses scala-reflect to get type info
Apache License 2.0
1 stars 2 forks source link

Sealed trait support #9

Closed pjfanning closed 2 years ago

pjfanning commented 2 years ago

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.