I have a short test program that fails to decode a jsonstring because the personId is missing in the jsonstring.
However, I have a default value set in the case class for personId based on zio documentation
https://zio.dev/zio-json/decoding#automatic-derivation-and-case-class-default-field-values
What am I doing wrong here ?
import zio.*
import zio.json.*
import zio.schema.{DeriveSchema, Schema}
final case class Person(personId: Long = 1, name: String, age: Int)
object Person {
implicit val decoder: JsonDecoder[Person] = DeriveJsonDecoder.gen[Person]
}
object MyApp extends ZIOAppDefault {
override def run: ZIO[Environment with ZIOAppArgs, Any, Any] =
for {
_ <- Console.printLine("Decoding a JSON string representing a person...")
jsonString =
"""
{
"name": "John",
"age": 30
}
""".stripMargin
result <- ZIO.fromEither(jsonString.fromJson[Person])
_ <- Console.printLine(s"Decoded Person: $result")
} yield ExitCode.success
}
Output:
Decoding a JSON string representing a person...
timestamp=2023-11-02T21:11:01.198368Z level=ERROR thread=#zio-fiber-1 message="" cause="Exception in thread "zio-fiber-4" java.lang.String: .personId(missing)
at <empty>.MyApp.run(MyApp2.scala:25)
at <empty>.MyApp.run(MyApp2.scala:27)"
Process finished with exit code 1
Versions:
val zioVersion = "2.0.13"
val zioJsonVersion = "0.5.0"
scala version 3.2.2
I was able to resolve this issue based on the help I got from discord community. There is a similar issue reported at https://github.com/zio/zio-json/issues/779
Solution is to set scala compiler option
-Yretain-trees