diff options
Diffstat (limited to 'src/main/scala/xyz/driver/pdsuidomain/formats')
-rw-r--r-- | src/main/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ListResponse.scala | 32 |
1 files changed, 15 insertions, 17 deletions
diff --git a/src/main/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ListResponse.scala b/src/main/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ListResponse.scala index 59a1a48..34cb7f1 100644 --- a/src/main/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ListResponse.scala +++ b/src/main/scala/xyz/driver/pdsuidomain/formats/json/sprayformats/ListResponse.scala @@ -2,15 +2,17 @@ package xyz.driver.pdsuidomain.formats.json.sprayformats import java.time.LocalDateTime -import spray.json.{RootJsonFormat, _} +import spray.json._ +import spray.json.DefaultJsonProtocol._ import xyz.driver.pdsuicommon.db.Pagination import xyz.driver.pdsuidomain.formats.json.sprayformats.common._ + final case class ListResponse[+T](items: Seq[T], meta: ListResponse.Meta) -object ListResponse extends DefaultJsonProtocol { +object ListResponse { private val itemsField = "items" - private val metaField = "meta" + private val metaField = "meta" final case class Meta(itemsCount: Int, pageNumber: Int, pageSize: Int, lastUpdate: Option[LocalDateTime]) @@ -27,31 +29,27 @@ object ListResponse extends DefaultJsonProtocol { implicit val listResponseMetaFormat: RootJsonFormat[Meta] = jsonFormat4(Meta.apply) - private def listResponseJsonWriter[T: JsonWriter](listResponse: ListResponse[T]) = { - JsObject( - itemsField -> listResponse.items.map(_.toJson).toJson, - metaField -> listResponse.meta.toJson - ) - } - implicit def listResponseWriter[T: JsonWriter]: RootJsonWriter[ListResponse[T]] = new RootJsonWriter[ListResponse[T]] { override def write(listResponse: ListResponse[T]): JsValue = { - listResponseJsonWriter(listResponse) + JsObject( + itemsField -> listResponse.items.map(_.toJson).toJson, + metaField -> listResponse.meta.toJson + ) } } - implicit def listResponseFormat[T: RootJsonFormat]: RootJsonFormat[ListResponse[T]] = - new RootJsonFormat[ListResponse[T]] { - override def write(listResponse: ListResponse[T]): JsValue = { - listResponseJsonWriter(listResponse) - } + implicit def listResponseReader[T: JsonReader]: RootJsonReader[ListResponse[T]] = + new RootJsonReader[ListResponse[T]] { override def read(json: JsValue): ListResponse[T] = json match { case JsObject(fields) => val items = fields .get(itemsField) - .map(_.convertTo[Seq[T]]) + .map{ + case JsArray(elements) => elements.map(_.convertTo[T])(collection.breakOut) + case x => deserializationError(s"Expected Array as JsArray, but got $x") + } .getOrElse(deserializationError(s"ListResponse json object does not contain `$itemsField` field: $json")) val meta = fields |