我有一个简短的测试程序,它无法解码jsonstring,因为jsonstring中缺少personId。
但是,我在case类中根据zio文档为personId设置了一个默认值
https://zio.dev/zio-json/decoding#automatic-derivation-and-case-class-default-field-values
我做错什么了?
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
}
字符串
输出:
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
型
版本:
val zioVersion = "2.0.13"
val zioJsonVersion = "0.5.0"
scala version 3.2.2
型
1条答案
按热度按时间cuxqih211#
我能够解决这个问题的基础上,我从discord社区得到的帮助。有一个类似的问题报告在https://github.com/zio/zio-json/issues/779
解决方法是设置scala编译器选项