Circe: Discriminator does not have effect when deriving sealed trait

Created on 15 Aug 2017  路  5Comments  路  Source: circe/circe

There's a problem with semiautomatic derivations with discriminator when deriving sealed trait.

object Adt {
  sealed trait Result
  case class SimpleResult(res: String) extends Result
  case class ResultWrapper(res: Result)
}

object Codec extends AutoDerivation {
  import io.circe.generic.semiauto._

  implicit val configuration: Configuration = Configuration.default
    .withDiscriminator("type")
    .withSnakeCaseConstructorNames
    .withSnakeCaseMemberNames

  implicit val encWrap: Encoder[Result] = deriveEncoder[Result]
}

object Application extends App {
  import Codec._

  val unwrappedEncoded = {
    val r: Result = SimpleResult("this is result")
    r.asJson.spaces2
  }

  println(s"Unwrapped Encoded: $unwrappedEncoded")
}

results into:

{
  "SimpleResult" : {
    "res" : "this is result"
  }
}

but expected result is:

{
    "res" : "this is result",
    "$type" : "simple_result"
  }

if I wrap result in ResultWrapper, result is correct.

Most helpful comment

Ok... You have wrong import. This is next fiddle that shows what is changed!
https://scalafiddle.io/sf/8XAonaP/4

assume that this issue should be closed!

All 5 comments

example copied to scalafiddle https://scalafiddle.io/sf/8XAonaP/0

Ok... You have wrong import. This is next fiddle that shows what is changed!
https://scalafiddle.io/sf/8XAonaP/4

assume that this issue should be closed!

@scalway thnx

@fr3akX , @scalway could you show right imports? I faced with the same issue, but link doesn't work

@feoktant
import io.circe.generic.extras._

Was this page helpful?
0 / 5 - 0 ratings