当我的案例 class 上有选项 [Instant] 属性 时,我的 JSON 读取未编译

My JSON reads is not compiling when there is an Option[Instant] property on my case class

如何为具有选项 Instant 属性 的 class 编写 json 读取?

case class User(id: Int, joined: Option[Instant])

我的 IDE 显示错误:

No implicit found for parameter: Reads[Option[Instant]]

implicit val userReads: Reads[User] = (
  (__\ "id").read[Int] and 
  (__ \ "joined").read[Option[Instant]]
 )(User.apply _ )

如果我删除选项,Instant 就可以正常工作。

为什么它不允许即时选项?

在这种情况下,您不应尝试解析 Option[T],而应使用 readNullable

import java.time.Instant

case class User(id: Int, joined: Option[Instant])

import play.api.libs.json._
import play.api.libs.functional.syntax._

implicit val userReads: Reads[User] = (
  (__ \ "id").read[Int] and 
  (__ \ "joined").readNullable[Instant]
 )(User.apply _)

此外,在这种情况下使用提供的宏更容易:

import java.time.Instant

case class User(id: Int, joined: Option[Instant])

import play.api.libs.json._

implicit val userReads: Reads[User] = Json.reads[User]