Skip to content

Commit

Permalink
Fix support of fieldName annotations in JSON codecs for case classes …
Browse files Browse the repository at this point in the history
…with 1 to 22 fields (#774)
  • Loading branch information
plokhotnyuk authored Jan 9, 2025
1 parent d24ae5f commit 7ee755e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1152,7 +1152,7 @@ object JsonCodec {
out.write(',')
if (doPrettyPrint) pad(indent_, out)
}
strEnc.unsafeEncode(schema.name, indent_, out)
strEnc.unsafeEncode(schema.fieldName, indent_, out)
if (doPrettyPrint) out.write(" : ")
else out.write(':')
enc.unsafeEncode(value, indent_, out)
Expand Down Expand Up @@ -1607,13 +1607,10 @@ object JsonCodec {
schema.fields.foreach { field =>
fields(idx) = field
decoders(idx) = schemaDecoder(field.schema)
val name = field.name.asInstanceOf[String]
val name = field.fieldName
names += name
spans += JsonError.ObjectAccess(name)
field.annotations.foreach {
case fna: fieldNameAliases => fna.aliases.foreach(a => aliases += ((a, idx)))
case _ =>
}
(field.nameAndAliases - name).foreach(a => aliases += ((a, idx)))
idx += 1
}
val hasDiscriminator = discriminator.isDefined
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -933,6 +933,13 @@ object JsonCodecSpec extends ZIOSpecDefault {
charSequenceToByteChunk("""{"id":1,"value":10,"description":"test"}""")
)
},
test("old field name rejected") {
assertDecodesToError(
Order.schema,
"""{"order-id":1,"value":10,"description":"test"}""",
JsonError.Message("missing") :: JsonError.ObjectAccess("orderId") :: Nil
)
},
test("field name with alias - no alias") {
assertDecodes(
Order.schema,
Expand Down Expand Up @@ -2310,7 +2317,11 @@ object JsonCodecSpec extends ZIOSpecDefault {
implicit lazy val schema: Schema[Subscription] = DeriveSchema.gen[Subscription]
}

case class Order(@fieldNameAliases("order_id", "id") orderId: Int, value: BigDecimal, description: String)
case class Order(
@fieldNameAliases("order_id", "id") @fieldName("orderId") `order-id`: Int,
value: BigDecimal,
description: String
)

object Order {
implicit lazy val schema: Schema[Order] = DeriveSchema.gen[Order]
Expand Down

0 comments on commit 7ee755e

Please sign in to comment.