Skip to content

Commit

Permalink
More efficient field decoder implementation for string-like values (#…
Browse files Browse the repository at this point in the history
…1251)

* More efficient field decoder implementation for string-like values

* Fix error messages for field decoder implementation of string-like values
  • Loading branch information
plokhotnyuk authored Jan 26, 2025
1 parent 96119fe commit 2a8edfb
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 8 deletions.
13 changes: 6 additions & 7 deletions zio-json/shared/src/main/scala/zio/json/JsonFieldDecoder.scala
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
*/
package zio.json

import zio.json.internal.Lexer
import zio.json.internal.{ FastStringReader, Lexer }
import zio.json.uuid.UUIDParser

/** When decoding a JSON Object, we only allow the keys that implement this interface. */
Expand Down Expand Up @@ -90,10 +90,9 @@ object JsonFieldDecoder extends LowPriorityJsonFieldDecoder {

private[json] trait LowPriorityJsonFieldDecoder {

def string: JsonFieldDecoder[String]

private def quotedString = string.map(raw => s""""$raw"""")

implicit def stringLike[T <: String: JsonDecoder]: JsonFieldDecoder[T] =
quotedString.mapOrFail(implicitly[JsonDecoder[T]].decodeJson)
implicit def stringLike[T <: String](implicit decoder: JsonDecoder[T]): JsonFieldDecoder[T] =
new JsonFieldDecoder[T] {
def unsafeDecodeField(trace: List[JsonError], in: String): T =
decoder.unsafeDecode(trace, new FastStringReader('"' + in + '"'))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ object DerivedDecoderSpec extends ZIOSpecDefault {
case class Foo(aOrB: Map["A" | "B", Int]) derives JsonDecoder

assertTrue("""{"aOrB": {"A": 1, "B": 2}}""".fromJson[Foo] == Right(Foo(Map("A" -> 1, "B" -> 2)))) &&
assertTrue("""{"aOrB": {"C": 1}}""".fromJson[Foo] == Left(".aOrB.C((expected one of: A, B))"))
assertTrue("""{"aOrB": {"C": 1}}""".fromJson[Foo] == Left(".aOrB.C(expected one of: A, B)"))
}
)
}

0 comments on commit 2a8edfb

Please sign in to comment.