如果class在scala 3.2.2中失败,但在2.13.8中成功,则使用默认值进行ZIO-JSON解码

atmip9wb  于 2023-11-18  发布在  Scala
关注(0)|答案(1)|浏览(217)

我有一个简短的测试程序,它无法解码jsonstring,因为jsonstring中缺少personId。
但是,我在case类中根据zio文档为personId设置了一个默认值
https://zio.dev/zio-json/decoding#automatic-derivation-and-case-class-default-field-values
我做错什么了?

  1. import zio.*
  2. import zio.json.*
  3. import zio.schema.{DeriveSchema, Schema}
  4. final case class Person(personId: Long = 1, name: String, age: Int)
  5. object Person {
  6. implicit val decoder: JsonDecoder[Person] = DeriveJsonDecoder.gen[Person]
  7. }
  8. object MyApp extends ZIOAppDefault {
  9. override def run: ZIO[Environment with ZIOAppArgs, Any, Any] =
  10. for {
  11. _ <- Console.printLine("Decoding a JSON string representing a person...")
  12. jsonString =
  13. """
  14. {
  15. "name": "John",
  16. "age": 30
  17. }
  18. """.stripMargin
  19. result <- ZIO.fromEither(jsonString.fromJson[Person])
  20. _ <- Console.printLine(s"Decoded Person: $result")
  21. } yield ExitCode.success
  22. }

字符串

输出

  1. Decoding a JSON string representing a person...
  2. 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)
  3. at <empty>.MyApp.run(MyApp2.scala:25)
  4. at <empty>.MyApp.run(MyApp2.scala:27)"
  5. Process finished with exit code 1

版本:

  1. val zioVersion = "2.0.13"
  2. val zioJsonVersion = "0.5.0"
  3. scala version 3.2.2

cuxqih21

cuxqih211#

我能够解决这个问题的基础上,我从discord社区得到的帮助。有一个类似的问题报告在https://github.com/zio/zio-json/issues/779

解决方法是设置scala编译器选项

  • Yretain树

相关问题