Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Scala 2.13: derivedConfiguratedEncoder becomes unconfigured under some conditions #2241

Open
Awethon opened this issue Mar 22, 2024 · 1 comment

Comments

@Awethon
Copy link

Awethon commented Mar 22, 2024

I am encountering an issue with Circe's deriveConfiguredEncoder in a Scala 2.13 project, where the derived encoder does not respect the custom discriminator configuration under certain conditions. Despite configuring Circe to use a custom discriminator ("type") via Configuration.default.withDiscriminator("type"), the derived encoders for sealed trait implementations do not include this discriminator in the output JSON.

import io.circe.{Codec, Decoder, Encoder, HCursor, Json, JsonObject}
import io.circe.generic.extras.Configuration
import io.circe.generic.extras.semiauto.{deriveConfiguredCodec, deriveConfiguredDecoder, deriveConfiguredEncoder}
import io.circe.parser._
import io.circe.syntax.EncoderOps

 object Identifier {
    sealed trait Id

    object Id {
      case class InternalId(id: String) extends Id
    }
  }

object codecs {
  import io.circe.Encoder
  import io.circe.generic.extras.Configuration
  import io.circe.generic.extras.semiauto.deriveConfiguredEncoder

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

  private def encoder1: Encoder[Identifier.Id.InternalId] = deriveConfiguredEncoder

  implicit def betterEncoder1: Encoder[Identifier.Id.InternalId] = encoder1(_)

  implicit def idEncoder: Encoder[Identifier.Id] = deriveConfiguredEncoder

}

println(codecs.idEncoder(Identifier.Id.InternalId("123456789")))

    // {
    //  "InternalId" : {
    //    "id" : "123456789"
    //  }
    //} was not equal to {
    //  "type" : "InternalId",
    //  "id" : "123456789",
    //}

scatie: https://scastie.scala-lang.org/MdeMaxnsRPOj6F56wCioWA

@Awethon
Copy link
Author

Awethon commented Mar 22, 2024

One possible workaround is to use Encoder.AsObject instead of Encoder and encodeObject instead of apply.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant