From 37d59546dc4bb467e181bd2c5db6a0e0f5fa9e2a Mon Sep 17 00:00:00 2001 From: Nabil Abdel-Hafeez <7283535+987Nabil@users.noreply.github.com> Date: Fri, 28 Jun 2024 10:02:52 +0200 Subject: [PATCH] Fix generic record construction for fields with fieldName annotation (#698) --- .../shared/src/main/scala-2/zio/schema/DeriveSchema.scala | 8 +++++--- .../src/main/scala/zio/schema/codec/JsonCodec.scala | 4 +++- .../src/test/scala-2/zio/schema/codec/JsonCodecSpec.scala | 2 +- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/zio-schema-derivation/shared/src/main/scala-2/zio/schema/DeriveSchema.scala b/zio-schema-derivation/shared/src/main/scala-2/zio/schema/DeriveSchema.scala index f5772dd7d..018079141 100644 --- a/zio-schema-derivation/shared/src/main/scala-2/zio/schema/DeriveSchema.scala +++ b/zio-schema-derivation/shared/src/main/scala-2/zio/schema/DeriveSchema.scala @@ -330,9 +330,11 @@ object DeriveSchema { } } val fromMap = { - val casts = fieldTypes.map { termSymbol => - q""" - try m.apply(${termSymbol.name.toString.trim}).asInstanceOf[${termSymbol.typeSignature}] + val casts = fieldTypes.zip(fieldAnnotations).map { + case (termSymbol, annotations) => + val newName = getFieldName(annotations).getOrElse(termSymbol.name.toString.trim) + q""" + try m.apply(${newName}).asInstanceOf[${termSymbol.typeSignature}] catch { case _: ClassCastException => throw new RuntimeException("Field " + ${termSymbol.name.toString.trim} + " has invalid type") case _: Throwable => throw new RuntimeException("Field " + ${termSymbol.name.toString.trim} + " is missing") 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 c11bea9f6..b72d8af6d 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 @@ -814,7 +814,9 @@ object JsonCodec { if (Lexer.firstField(trace, in)) { while ({ val field = Lexer.string(trace, in).toString - structure.find(_.name == field) match { + structure.find( + f => f.name == field || f.annotations.collectFirst { case fieldName(name) => name }.contains(field) + ) match { case Some(Schema.Field(label, schema, _, _, _, _)) => val trace_ = JsonError.ObjectAccess(label) :: trace Lexer.char(trace_, in, ':') 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 aeb062fb9..115bee8e5 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 @@ -1906,7 +1906,7 @@ object JsonCodecSpec extends ZIOSpecDefault { f20: Option[String] = None, f21: Option[String] = None, f22: Option[String] = None, - f23: Option[String] = None + @fieldName("$f23") f23: Option[String] = None ) object RecordExample {