From 8506c369818228b77458efe248767c311e37ffee Mon Sep 17 00:00:00 2001 From: Simon Schenk Date: Mon, 22 Apr 2024 09:43:55 +0200 Subject: [PATCH] fix: decode ADT with 3 cases with noDiscriminator --- .../scala/zio/schema/codec/JsonCodec.scala | 3 ++- .../zio/schema/codec/JsonCodecSpec.scala | 26 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/zio-schema-json/shared/src/main/scala/zio/schema/codec/JsonCodec.scala b/zio-schema-json/shared/src/main/scala/zio/schema/codec/JsonCodec.scala index 582eff73e..758b5adbd 100644 --- a/zio-schema-json/shared/src/main/scala/zio/schema/codec/JsonCodec.scala +++ b/zio-schema-json/shared/src/main/scala/zio/schema/codec/JsonCodec.scala @@ -711,7 +711,7 @@ object JsonCodec { (trace: List[JsonError], in: RetractReader) => { if (noDiscriminators) { - val rr = RecordingReader(in) + var rr = RecordingReader(in) val it = cases.iterator var result: Option[Z] = None @@ -723,6 +723,7 @@ object JsonCodec { } catch { case _: Exception => rr.rewind() + if (result.isEmpty && it.hasNext) rr = RecordingReader(rr) } } diff --git a/zio-schema-json/shared/src/test/scala-2/zio/schema/codec/JsonCodecSpec.scala b/zio-schema-json/shared/src/test/scala-2/zio/schema/codec/JsonCodecSpec.scala index 243ef029e..923c19da5 100644 --- a/zio-schema-json/shared/src/test/scala-2/zio/schema/codec/JsonCodecSpec.scala +++ b/zio-schema-json/shared/src/test/scala-2/zio/schema/codec/JsonCodecSpec.scala @@ -1184,6 +1184,18 @@ object JsonCodecSpec extends ZIOSpecDefault { Enumeration2(BooleanValue2(false)) ) }, + test("ADT with noDiscriminator") { + assertEncodesThenDecodes( + Schema[Enumeration3], + Enumeration3(StringValue3("foo")) + ) &> assertEncodesThenDecodes( + Schema[Enumeration3], + Enumeration3(StringValue3Multi("foo", "bar")) + ) &> assertEncodesThenDecodes(Schema[Enumeration3], Enumeration3(IntValue3(-1))) &> assertEncodesThenDecodes( + Schema[Enumeration3], + Enumeration3(BooleanValue3(false)) + ) &> assertEncodesThenDecodes(Schema[Enumeration3], Enumeration3(Nested(StringValue3("foo")))) + }, test("of case classes with discriminator") { assertEncodesThenDecodes(Schema[Command], Command.Cash) &> assertEncodesThenDecodes(Schema[Command], Command.Buy(100)) @@ -1673,6 +1685,20 @@ object JsonCodecSpec extends ZIOSpecDefault { implicit val schema: Schema[Enumeration2] = DeriveSchema.gen[Enumeration2] } + @noDiscriminator + sealed trait OneOf3 + case class StringValue3(value: String) extends OneOf3 + case class IntValue3(value: Int) extends OneOf3 + case class BooleanValue3(value: Boolean) extends OneOf3 + case class StringValue3Multi(value1: String, value2: String) extends OneOf3 + case class Nested(oneOf: OneOf3) extends OneOf3 + + case class Enumeration3(oneOf: OneOf3) + + object Enumeration3 { + implicit val schema: Schema[Enumeration3] = DeriveSchema.gen[Enumeration3] + } + sealed trait Color object Color {