Created
March 9, 2019 01:41
-
-
Save borice/5aff731988a54b978ed9ab298361b501 to your computer and use it in GitHub Desktop.
Converts LocalDate and Instant from java.time to/from Play JSON for MongoDB use
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.time.{Instant, LocalDate, ZoneOffset} | |
import play.api.libs.json._ | |
object JsonImplicits { | |
implicit object LocalDateMongoJsonReaderWriter extends Reads[LocalDate] with Writes[LocalDate] { | |
override def reads(json: JsValue): JsResult[LocalDate] = | |
(json \ "$date").validate[Long].map(Instant.ofEpochMilli(_).atZone(ZoneOffset.UTC).toLocalDate) | |
override def writes(date: LocalDate): JsValue = | |
Json.obj("$date" -> date.atStartOfDay().atZone(ZoneOffset.UTC).toInstant.toEpochMilli) | |
} | |
implicit object InstantMongoJsonReaderWriter extends Reads[Instant] with Writes[Instant] { | |
override def reads(json: JsValue): JsResult[Instant] = | |
(json \ "$date").validate[Long].map(Instant.ofEpochMilli) | |
override def writes(instant: Instant): JsValue = | |
Json.obj("$date" -> instant.toEpochMilli) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment