Skip to content

Instantly share code, notes, and snippets.

@ephemeralsnow
Created October 23, 2014 06:02
Show Gist options
  • Save ephemeralsnow/7ce618d85e526b6dcf19 to your computer and use it in GitHub Desktop.
Save ephemeralsnow/7ce618d85e526b6dcf19 to your computer and use it in GitHub Desktop.
Java8 Date and Time API の java.time.Instant に対応させる play.api.libs.json.{Reads, Writes, Format}
package helpers.play.api.libs.json
import play.api.data.validation.ValidationError
import play.api.libs.json._
/**
* @see play.api.libs.json.Reads
*/
object InstantReads {
def instantReads(formatter: java.time.format.DateTimeFormatter = java.time.format.DateTimeFormatter.ISO_INSTANT, corrector: String => String = identity): Reads[java.time.Instant] = new Reads[java.time.Instant] {
def reads(json: JsValue): JsResult[java.time.Instant] = json match {
case JsNumber(d) => JsSuccess(java.time.Instant.ofEpochMilli(d.toLong))
case JsString(s) => parseDate(corrector(s)) match {
case Some(d) => JsSuccess(d)
case None => JsError(Seq(JsPath() -> Seq(ValidationError("error.expected.date.isoformat", formatter))))
}
case _ => JsError(Seq(JsPath() -> Seq(ValidationError("error.expected.date"))))
}
private def parseDate(input: String): Option[java.time.Instant] = {
try {
Some(java.time.Instant.from(formatter.parse(input)))
} catch {
case _: java.time.format.DateTimeParseException => None
}
}
}
implicit val IsoInstantReads = instantReads(java.time.format.DateTimeFormatter.ISO_INSTANT)
}
package helpers.play.api.libs.json
import play.api.libs.json._
/**
* @see play.api.libs.json.Writes
*/
object InstantWrites {
def instantWrites(formatter: java.time.format.DateTimeFormatter): Writes[java.time.Instant] = new Writes[java.time.Instant] {
def writes(d: java.time.Instant): JsValue = JsString(formatter.format(d))
}
implicit val IsoInstantWrites = instantWrites(java.time.format.DateTimeFormatter.ISO_INSTANT)
}
package helpers.play.api.libs.json
import play.api.libs.json.Format
/**
* @see play.api.libs.json.Format
*/
object InstantFormat {
implicit val IsoInstantFormat = Format(InstantReads.IsoInstantReads, InstantWrites.IsoInstantWrites)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment