From 0ca4befab8aceb8008ffa3c7afc472528232f717 Mon Sep 17 00:00:00 2001 From: Stewart Stewart Date: Tue, 31 Jan 2017 23:22:59 -0500 Subject: serialize date to ISO string rather than object --- src/main/scala/xyz/driver/core/json.scala | 21 +++++++++++---------- src/test/scala/xyz/driver/core/JsonTest.scala | 6 +----- 2 files changed, 12 insertions(+), 15 deletions(-) diff --git a/src/main/scala/xyz/driver/core/json.scala b/src/main/scala/xyz/driver/core/json.scala index 039f650..9a7672e 100644 --- a/src/main/scala/xyz/driver/core/json.scala +++ b/src/main/scala/xyz/driver/core/json.scala @@ -7,14 +7,12 @@ import akka.http.scaladsl.unmarshalling.Unmarshaller import spray.json.{DeserializationException, JsNumber, _} import xyz.driver.core.revision.Revision import xyz.driver.core.time.Time -import xyz.driver.core.date.{Date, Month} +import xyz.driver.core.date.Date import scala.reflect.runtime.universe._ object json { - import DefaultJsonProtocol._ - def IdInPath[T]: PathMatcher1[Id[T]] = new PathMatcher1[Id[T]] { def apply(path: Path) = path match { case Path.Segment(segment, tail) => Matched(tail, Tuple1(Id[T](segment))) @@ -69,16 +67,19 @@ object json { } } - implicit val monthFormat = new RootJsonFormat[Month] { - def write(month: Month) = JsNumber(month) - def read(value: JsValue): Month = value match { - case JsNumber(month) if 0 <= month && month <= 11 => date.tagMonth(month.toInt) - case _ => throw DeserializationException("Expected a number from 0 to 11") + implicit val dateFormat = new JsonFormat[Date] { + def write(date: Date) = JsString(date.toString) + def read(value: JsValue): Date = value match { + case JsString(dateString) => + Date + .fromString(dateString) + .getOrElse( + throw new DeserializationException( + s"Misformated ISO 8601 Date. Expected YYYY-MM-DD, but got $dateString.")) + case _ => throw new DeserializationException(s"Date expects a string, but got $value.") } } - implicit val dateFormat = jsonFormat3(Date.apply) - def RevisionInPath[T]: PathMatcher1[Revision[T]] = PathMatcher("""[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}""".r) flatMap { string => Some(Revision[T](string)) diff --git a/src/test/scala/xyz/driver/core/JsonTest.scala b/src/test/scala/xyz/driver/core/JsonTest.scala index 821b162..ff804a9 100644 --- a/src/test/scala/xyz/driver/core/JsonTest.scala +++ b/src/test/scala/xyz/driver/core/JsonTest.scala @@ -48,11 +48,7 @@ class JsonTest extends FlatSpec with Matchers { val referenceDate = Date(1941, Month.DECEMBER, 7) val writtenJson = json.dateFormat.write(referenceDate) - writtenJson.prettyPrint should be("""|{ - | "year": 1941, - | "month": 11, - | "day": 7 - |}""".stripMargin) + writtenJson.prettyPrint should be("\"1941-12-07\"") val parsedDate = json.dateFormat.read(writtenJson) parsedDate should be(referenceDate) -- cgit v1.2.3