Skip to content

Commit 37d5954

Browse files
authored
Fix generic record construction for fields with fieldName annotation (#698)
1 parent e3ede68 commit 37d5954

File tree

3 files changed

+9
-5
lines changed

3 files changed

+9
-5
lines changed

zio-schema-derivation/shared/src/main/scala-2/zio/schema/DeriveSchema.scala

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -330,9 +330,11 @@ object DeriveSchema {
330330
}
331331
}
332332
val fromMap = {
333-
val casts = fieldTypes.map { termSymbol =>
334-
q"""
335-
try m.apply(${termSymbol.name.toString.trim}).asInstanceOf[${termSymbol.typeSignature}]
333+
val casts = fieldTypes.zip(fieldAnnotations).map {
334+
case (termSymbol, annotations) =>
335+
val newName = getFieldName(annotations).getOrElse(termSymbol.name.toString.trim)
336+
q"""
337+
try m.apply(${newName}).asInstanceOf[${termSymbol.typeSignature}]
336338
catch {
337339
case _: ClassCastException => throw new RuntimeException("Field " + ${termSymbol.name.toString.trim} + " has invalid type")
338340
case _: Throwable => throw new RuntimeException("Field " + ${termSymbol.name.toString.trim} + " is missing")

zio-schema-json/shared/src/main/scala/zio/schema/codec/JsonCodec.scala

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -814,7 +814,9 @@ object JsonCodec {
814814
if (Lexer.firstField(trace, in)) {
815815
while ({
816816
val field = Lexer.string(trace, in).toString
817-
structure.find(_.name == field) match {
817+
structure.find(
818+
f => f.name == field || f.annotations.collectFirst { case fieldName(name) => name }.contains(field)
819+
) match {
818820
case Some(Schema.Field(label, schema, _, _, _, _)) =>
819821
val trace_ = JsonError.ObjectAccess(label) :: trace
820822
Lexer.char(trace_, in, ':')

zio-schema-json/shared/src/test/scala-2/zio/schema/codec/JsonCodecSpec.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1906,7 +1906,7 @@ object JsonCodecSpec extends ZIOSpecDefault {
19061906
f20: Option[String] = None,
19071907
f21: Option[String] = None,
19081908
f22: Option[String] = None,
1909-
f23: Option[String] = None
1909+
@fieldName("$f23") f23: Option[String] = None
19101910
)
19111911

19121912
object RecordExample {

0 commit comments

Comments
 (0)