Deserializing nested polymorphic fields

Viewed 333

Is it possible to deserialize the following JSON

{
  "operation": "create", // type discriminator
  "value": "some text",
  "source": {
    "name": "source name",
    "kind": "db" // type discriminator
  }
}

to the following set of classes

sealed trait Source

case class DbSource(name: String) extends Source

sealed trait Operation

case class CreateOperation(value: String, source: Source) extends Operation

using Json4s without resorting to custom deserializers?

3 Answers

The Json library Circe offers exactly what you are looking for: The relevant page

implicit val sourceConfig: Configuration =
  Configuration.default.withDiscriminator("operation")

Use typeHint field https://github.com/json4s/json4s#serializing-polymorphic-lists you can change also this discriminator field name ie:

implicit val customFormats: Formats =
      new DefaultFormats {
        override val typeHintFieldName   = "className"

this example is using field className for all type of traits->case classes.

Related