Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat-string-like-field-decoder #1137

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion zio-json/shared/src/main/scala/zio/json/JsonFieldDecoder.scala
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ trait JsonFieldDecoder[+A] {
def unsafeDecodeField(trace: List[JsonError], in: String): A
}

object JsonFieldDecoder {
object JsonFieldDecoder extends LowPriorityJsonFieldDecoder {
def apply[A](implicit a: JsonFieldDecoder[A]): JsonFieldDecoder[A] = a

implicit val string: JsonFieldDecoder[String] = new JsonFieldDecoder[String] {
Expand Down Expand Up @@ -87,3 +87,13 @@ object JsonFieldDecoder {
if (s.length <= len) s
else s.substring(0, len) + "..."
}

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)
}
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,12 @@ object DerivedDecoderSpec extends ZIOSpecDefault {

assertTrue("""{"aOrB": "A", "optA": "A"}""".fromJson[Foo] == Right(Foo("A", Some("A")))) &&
assertTrue("""{"aOrB": "C"}""".fromJson[Foo] == Left(".aOrB(expected one of: A, B)"))
},
test("Derives and decodes for a custom map key string-based union type") {
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))"))
}
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,11 @@ object DerivedEncoderSpec extends ZIOSpecDefault {
case class Foo(aOrB: "A" | "B", optA: Option["A"]) derives JsonEncoder

assertTrue(Foo("A", Some("A")).toJson == """{"aOrB":"A","optA":"A"}""")
},
test("Derives and encodes for a custom map key string-based union type") {
case class Foo(aOrB: Map["A" | "B", Int]) derives JsonEncoder

assertTrue(Foo(Map("A" -> 1, "B" -> 2)).toJson == """{"aOrB":{"A":1,"B":2}}""")
}
)
}