zio-json
zio-json copied to clipboard
Implement inheritDiscriminator annotation
This is a different approach than #1112. The PR implements a inheritDiscriminator
annotation to be used on case classes. If the parent class doesn't have a jsonDiscriminator
annotation it will throw a compilation error when deriving a codec. When there is a jsonDiscriminator
it will include this in the encoding with the name of the case class or the jsonHint
.
I don't know if this is the exact use case of @alphaho, but I guess it might be encoding and decoding with different encoders for convenience when interacting between different parts of the code base. In these cases it might be easier to use something like this annotation. And this isn't a breaking change. What do you think @987Nabil? fixes #1056 /claim #1056
The final code for the example of @alphaho would be
import zio.json._
@jsonDiscriminator("type")
sealed trait Animal
object Animal {
@inheritDiscriminator @jsonHint("dog")
case class Dog(name: String) extends Animal
object Dog {
implicit val dogCodec: JsonCodec[Dog] = DeriveJsonCodec.gen
}
@inheritDiscriminator @jsonHint("cat")
case class Cat(name: String, weight: Double) extends Animal
implicit val animalCodec: JsonCodec[Animal] = DeriveJsonCodec.gen
}