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

Respect discriminators of object enums in Scala 3 #1160

Merged
merged 1 commit into from
Sep 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions zio-json/shared/src/main/scala-3/zio/json/macros.scala
Original file line number Diff line number Diff line change
Expand Up @@ -409,7 +409,7 @@ object DeriveJsonDecoder extends Derivation[JsonDecoder] { self =>

def discrim = ctx.annotations.collectFirst { case jsonDiscriminator(n) => n }

if (isEnumeration) {
if (isEnumeration && discrim.isEmpty) {
new JsonDecoder[A] {
def unsafeDecode(trace: List[JsonError], in: RetractReader): A = {
val typeName = Lexer.string(trace, in).toString()
Expand Down Expand Up @@ -656,7 +656,7 @@ object DeriveJsonEncoder extends Derivation[JsonEncoder] { self =>
case jsonDiscriminator(n) => n
}

if (isEnumeration) {
if (isEnumeration && discrim.isEmpty) {
new JsonEncoder[A] {
def unsafeEncode(a: A, indent: Option[Int], out: Write): Unit = {
val typeName = ctx.choose(a) { sub =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,18 @@ object DerivedDecoderSpec extends ZIOSpecDefault {

assertTrue(result == Right(Foo.Qux))
},
test("Derives for a sum sealed trait Enumeration type with discriminator") {
@jsonDiscriminator("$type")
sealed trait Foo derives JsonDecoder
object Foo:
case object Bar extends Foo
case object Baz extends Foo
case object Qux extends Foo

val result = """{"$type":"Qux"}""".fromJson[Foo]

assertTrue(result == Right(Foo.Qux))
},
test("Derives for a sum ADT type") {
enum Foo derives JsonDecoder:
case Bar
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,17 @@ object DerivedEncoderSpec extends ZIOSpecDefault {

assertTrue(json == """"Qux"""")
},
test("Derives for a sum enum Enumeration type with discriminator") {
@jsonDiscriminator("$type")
enum Foo derives JsonEncoder:
case Bar
case Baz
case Qux

val json = (Foo.Qux: Foo).toJson

assertTrue(json == """{"$type":"Qux"}""")
},
test("Derives for a sum sealed trait Enumeration type") {
sealed trait Foo derives JsonEncoder
object Foo:
Expand Down
Loading