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

DeriveJsonEncoder and DeriveJsonDecoder don't pick up implicit Codec instances #867

Open
leszekgruchala opened this issue Jan 25, 2023 · 0 comments

Comments

@leszekgruchala
Copy link

The DeriveJsonEncoder and DeriveJsonDecoder don't pick up implicit Codec instances so it is not possible to override their behavior.

I had my custom implicit JsonCodec[Instant] because I don't want my Instants to be decoded as Strings, but numbers:

implicit val InstantJsonCodec: JsonCodec[Instant] = JsonCodec(
    JsonEncoder.long.contramap[Instant](_.toEpochMilli),
    JsonDecoder.long.map(Instant.ofEpochMilli)
  )

unfortunately, even though this implicit is in the scope, the derived JsonCodec ignores it and keeps returning a string

case class MyDTO(
  id: Int,
  startAt: Instant
)

object MyDTO {

  implicit val InstantJsonCodec: JsonCodec[Instant] = JsonCodec(
    JsonEncoder.long.contramap[Instant](_.toEpochMilli),
    JsonDecoder.long.map(Instant.ofEpochMilli)
  )

  implicit val codec: JsonCodec[MyDTO] = JsonCodec(
    DeriveJsonEncoder.gen,
    DeriveJsonDecoder.gen
  )
}

Example: https://scastie.scala-lang.org/V2A1rnwwQAGVtjSILEe71g

Fortunately, there is a workaround. We need to define the encoder and decoder directly.
DeriveJsonEncoder doesn’t pick up the implicit Codec, only implicit Encoders.

Workound: https://scastie.scala-lang.org/V2A1rnwwQAGVtjSILEe71g

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