zio / zio-json

Fast, secure JSON library with tight ZIO integration.
https://zio.dev/zio-json
Apache License 2.0
401 stars 143 forks source link

How to decode a specific enum/sealed trait subtype with discriminator #1112

Open 987Nabil opened 1 month ago

987Nabil commented 1 month ago

After thinking about the suggestions made in the issue, I think they are not desirable for default behaviour.

  1. Repurposing of @jsonDiscriminator can not only lead to inconsistencies, but is unintuitive and very strange when applied to a case class that is not part of a sealed hierarchy.
  2. Deriving the codec of the subtype and reading config from the parent seems odd as well. The code DeriveJsonCodec.gen[Dog] asks very explicitly for a Dog codec, but in my opinion the Dog codec should not be aware of it being a subtype of a sealed trait here at all. This is not only more consistent, but I would argue this change would be a breaking one. A codec that might be currently derived and works well, would suddenly fail, if this is implemented and released. And wanting a codec that treats Dog just as a case class is also reasonable.

Over all, I don't see any of these solutions as a good one. The idea is somehow to fit the derivation to some personal needs. And they don't see common to me. I decided instead to add docs how to create a custom Decoder that fails when the wrong structure is found.

Another option could be to implement #689 and define the decoder by hand.

fixes #1056 /claim #1056