How do I write the json reads for a class that has an option Instant property?
case class User(id: Int, joined: Option[Instant])
My IDE is showing the error:
No implicit found for parameter: Reads[Option[Instant]]
implicit val userReads: Reads[User] = (
(__\ "id").read[Int] and
(__ \ "joined").read[Option[Instant]]
)(User.apply _ )
If I remove the Option than the Instant works fine.
Why doesn't it allow the options for an Instant?
You should not try to resolve Option[T]
in such case, but use 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 _)
Also, it easier in such case to use the provided macro:
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]