I am writing a case class that will map to a JSON result that I am getting from an external API response.
The datetime looks like: 2016-05-30T00:23:27.070Z
What type should I use to map to this datetime string?
I want to use playframework's json automapper so I can just do:
implicit val userReads = Json.reads[User]
case class User(createdAt: ?????)
答案 0 :(得分:2)
There is already predefined Format for dates DefaultLocalDateTimeReads
:
import java.time.LocalDateTime
val json = Json.parse("""{"date": "2016-05-30T00:23:27.070Z"}""")
(json \ "date").as[LocalDateTime]
In case you need some other dateTime library/format, you could write custom reader like this one:
import org.joda.time.DateTime
import play.api.libs.json.{JsError, _}
implicit object DateTimeReads extends Reads[DateTime] {
val Format = org.joda.time.format.DateTimeFormat
.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
def reads(json: JsValue) = json match {
case JsString(x) => JsSuccess(Format.parseDateTime(x))
case _ => JsError(s"Can't read $json as DateTime")
}
}
(json \ "date").as[DateTime]
res0: org.joda.time.DateTime = 2016-05-30T00:23:27.070+03:00
答案 1 :(得分:0)
import java.time.LocalDateTime
case class User(createdAt: LocalDateTime)
implicit val userReads = Json.reads[User]