本文整理汇总了Scala中spray.json.JsonFormat类的典型用法代码示例。如果您正苦于以下问题:Scala JsonFormat类的具体用法?Scala JsonFormat怎么用?Scala JsonFormat使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了JsonFormat类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: SendTweet
//设置package包名称以及导入依赖的类
package main.scala
import scala.collection.mutable.ArrayBuffer
import spray.json.DefaultJsonProtocol
import spray.json.DeserializationException
import spray.json.JsArray
import spray.json.JsNumber
import spray.json.JsObject
import spray.json.JsString
import spray.json.JsValue
import spray.json.JsonFormat
import spray.json.pimpAny
trait JsonFormats extends DefaultJsonProtocol {
case class SendTweet(userId: Int, time: Long, msg: String)
case class UserProfile(id: Int, name: String, statusCount: Int, favoritesCount: Int, followersCount: Int, followingCount: Int)
case class SendMsg(senderId: Int, time: Long, msg: String, recepientId: Int)
implicit val tweetFormat = jsonFormat3(SendTweet)
implicit val userProfileFormat = jsonFormat6(UserProfile)
implicit val reTweetFormat = jsonFormat4(SendMsg)
implicit object TimelineJsonFormat extends JsonFormat[Project4Server.Tweets] {
def write(c: Project4Server.Tweets) = JsObject(
"authorId" -> JsNumber(c.authorId),
"message" -> JsString(c.message),
"timeStamp" -> JsString(c.timeStamp.toString),
"tweetId" -> JsString(c.tweetId),
"mentions" -> JsArray(c.mentions.map(_.toJson).toVector),
"hashTags" -> JsArray(c.hashtags.map(_.toJson).toVector))
def read(value: JsValue) = {
value.asJsObject.getFields("tweetId", "authorId", "message", "timeStamp", "mentions", "hashTags") match {
case Seq(JsString(tweetId), JsNumber(authorId), JsString(message), JsString(timeStamp), JsArray(mentions), JsArray(hashTags)) =>
new Project4Server.Tweets(tweetId, authorId.toInt, message, timeStamp.toLong, mentions.map(_.convertTo[String]).to[ArrayBuffer], hashTags.map(_.convertTo[String]).to[ArrayBuffer])
case _ => throw new DeserializationException("Tweets expected")
}
}
}
implicit object MessagesJsonFormat extends JsonFormat[Project4Server.Messages] {
def write(c: Project4Server.Messages) = JsObject(
"authorId" -> JsNumber(c.authorId),
"message" -> JsString(c.message),
"timeStamp" -> JsString(c.timeStamp.toString),
"tweetId" -> JsString(c.tweetId),
"mentions" -> JsArray(c.mentions.map(_.toJson).toVector),
"hashTags" -> JsArray(c.hashtags.map(_.toJson).toVector),
"recepientId" -> JsNumber(c.recepientId))
def read(value: JsValue) = {
value.asJsObject.getFields("tweetId", "authorId", "message", "timeStamp", "mentions", "hashTags", "recepientId") match {
case Seq(JsString(tweetId), JsNumber(authorId), JsString(message), JsString(timeStamp), JsArray(mentions), JsArray(hashTags), JsNumber(recepientId)) =>
new Project4Server.Messages(recepientId.toInt, tweetId, authorId.toInt, message, timeStamp.toLong, mentions.map(_.convertTo[String]).to[ArrayBuffer], hashTags.map(_.convertTo[String]).to[ArrayBuffer])
case _ => throw new DeserializationException("Tweets expected")
}
}
}
}
示例2: getStackTrace
//设置package包名称以及导入依赖的类
package proton.users
import java.io.{PrintWriter, StringWriter}
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.UUID
import spray.json.{JsValue, JsonFormat, _}
trait UsersProtocol {
private def getStackTrace(t: Throwable) = {
val sw: StringWriter = new StringWriter()
val pw: PrintWriter = new PrintWriter(sw)
t.printStackTrace(pw)
sw.toString
}
implicit object ThrowableWriter extends RootJsonWriter[Throwable] {
def write(t: Throwable) = JsObject(
"message" -> JsString(t.getMessage),
"cause" -> t.getCause.toJson,
"stackTrace" -> JsString(getStackTrace(t))
)
}
implicit object MessageFormat extends RootJsonWriter[Message] {
def write(m: Message) = JsObject(
"summary" -> JsString(m.summary),
"errorCode" -> JsNumber(m.errorCode)
)
}
implicit object ValidationFormat extends RootJsonWriter[Validation] {
def write(v: Validation) = {
val fields = Seq[Option[JsField]](
Some("message" -> JsString(v.message)),
Some("errorCode" -> JsNumber(v.errorCode)),
v.exception.map(exception => "exception" -> exception.toJson)
)
JsObject(fields.flatten: _*)
}
}
implicit object UUIDFormat extends JsonFormat[UUID] {
def write(uuid: UUID) = JsString(uuid.toString)
def read(value: JsValue) = value match {
case JsString(uuid) => UUID.fromString(uuid)
case _ => deserializationError("UUID expected.")
}
}
implicit object LocalDateTimeFormat extends JsonFormat[LocalDateTime] {
def write(dateTime: LocalDateTime) = JsString(dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME))
def read(value: JsValue) = value match {
case JsString(dateTime) => LocalDateTime.parse(dateTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME)
case _ => deserializationError("LocalDateTime expected.")
}
}
}
示例3: SearchResult
//设置package包名称以及导入依赖的类
package au.csiro.data61.magda.api.model
import au.csiro.data61.magda.model.misc.{ DataSet, Facet, Region }
import au.csiro.data61.magda.model.Temporal
import au.csiro.data61.magda.model.misc
import au.csiro.data61.magda.search.SearchStrategy
import spray.json.{ DefaultJsonProtocol, JsString, JsValue, JsonFormat }
import au.csiro.data61.magda.api.{ Query, FilterValue, Specified, Unspecified }
import au.csiro.data61.magda.model.misc.{ QueryRegion }
import java.time.OffsetDateTime
import com.typesafe.config.Config
case class SearchResult(
query: Query,
hitCount: Long,
facets: Option[Seq[Facet]] = None,
dataSets: List[DataSet],
errorMessage: Option[String] = None,
strategy: Option[SearchStrategy] = None)
case class RegionSearchResult(
query: String,
hitCount: Long,
regions: List[Region])
trait Protocols extends DefaultJsonProtocol with Temporal.Protocols with misc.Protocols {
implicit object SearchStrategyFormat extends JsonFormat[SearchStrategy] {
override def write(strat: SearchStrategy): JsString = JsString.apply(strat.name)
override def read(json: JsValue): SearchStrategy = SearchStrategy.parse(json.convertTo[String])
}
class FilterValueFormat[T](implicit t: JsonFormat[T], implicit val config: Config) extends JsonFormat[FilterValue[T]] {
override def write(filterValue: FilterValue[T]): JsValue = filterValue match {
case Specified(inner) => t.write(inner)
case Unspecified() => JsString(filterValue.toString)
}
override def read(json: JsValue): FilterValue[T] = json match {
case JsString(string) =>
if (string.toLowerCase.equals(Unspecified().toString.toLowerCase()))
Unspecified() else Specified(t.read(json))
case other => Specified(t.read(other))
}
}
implicit def stringFilterValueFormat(implicit config: Config) = new FilterValueFormat[String]
implicit def offsetDateFilterValueFormat(implicit config: Config) = new FilterValueFormat[OffsetDateTime]
implicit def queryRegionFilterValueFormat(implicit config: Config) = new FilterValueFormat[Region]()(apiRegionFormat, config)
implicit def queryFormat(implicit config: Config) = jsonFormat8(Query.apply)
implicit def searchResultFormat(implicit config: Config) = jsonFormat6(SearchResult.apply)
implicit val regionSearchResultFormat = {
implicit val regionFormat = apiRegionFormat
jsonFormat3(RegionSearchResult.apply)
}
}
object Protocols extends Protocols {
}
示例4: UUIDJsonProtocol
//设置package包名称以及导入依赖的类
package example.http.json
import java.util.UUID
import spray.json.{ DefaultJsonProtocol, JsString, JsValue, JsonFormat }
import spray.json._
object UUIDJsonProtocol extends DefaultJsonProtocol {
implicit object UUIDJsonFormat extends JsonFormat[UUID] {
override def read(json: JsValue): UUID = json match {
case JsString(value) =>
try {
UUID.fromString(value)
} catch {
case ex: IllegalArgumentException => error(value)
}
case _ =>
error(json.toString())
}
override def write(obj: UUID): JsValue =
JsString(obj.toString)
def error(v: Any): UUID = {
val example = UUID.randomUUID()
deserializationError(f"'$v' is not a valid UUID value., e.g. '$example'")
}
}
}
示例5: ServiceApi
//设置package包名称以及导入依赖的类
package com.github.cupenya.authorization.server
import akka.http.scaladsl.model.StatusCode
import spray.json.JsonFormat
sealed trait ServiceApi
object ServiceApi extends spray.json.DefaultJsonProtocol {
implicit val errorDataFormat = jsonFormat3(ErrorData)
implicit val serviceResponseErrorFormat = jsonFormat2(ServiceResponseError)
}
case object NotOk extends ResponseStatus
}
case class ServiceResponse[T: JsonFormat](
success: Boolean,
data: Option[T],
error: Option[ServiceResponseError]
)
extends ServiceApi
case class ServiceResponseError(
message: String,
data: Option[List[ErrorData]]
)
extends ServiceApi
case class ErrorData(
field: String,
message: String,
messageCode: String
)
extends ServiceApi
示例6: serviceSuccessJsonFormat
//设置package包名称以及导入依赖的类
package api.json
import common.{ErrorMessage, ServiceSuccess}
import spray.json.{DefaultJsonProtocol, DeserializationException, JsBoolean, JsFalse, JsObject, JsString, JsTrue, JsValue, JsonFormat, RootJsonFormat}
trait CommonJsonProtocol {
this: DefaultJsonProtocol =>
implicit def serviceSuccessJsonFormat[A](implicit format: JsonFormat[A]) = new RootJsonFormat[ServiceSuccess[A]] {
override def write(value: ServiceSuccess[A]): JsValue = {
JsObject("ok" -> JsBoolean(true), "result" -> format.write(value.result))
}
override def read(json: JsValue): ServiceSuccess[A] = {
val root = json.asJsObject
(root.fields.get("ok"), root.fields.get("result")) match {
case (Some(JsTrue), Some(jsValue)) => ServiceSuccess(format.read(jsValue))
case _ => throw new DeserializationException("JSON not a ServiceSuccess")
}
}
}
implicit object errorMessageJsonFormat extends RootJsonFormat[ErrorMessage] {
override def write(value: ErrorMessage): JsValue = {
JsObject("ok" -> JsBoolean(false), "error" -> JsString(value.text))
}
override def read(json: JsValue): ErrorMessage = {
val root = json.asJsObject
(root.fields.get("ok"), root.fields.get("error")) match {
case (Some(JsFalse), Some(JsString(errorText))) => new ErrorMessage {
val text = errorText
}
case _ => throw new DeserializationException("JSON not a ErrorMessage")
}
}
}
implicit def rootEitherFormat[A : RootJsonFormat, B : RootJsonFormat] = new RootJsonFormat[Either[A, B]] {
val format = DefaultJsonProtocol.eitherFormat[A, B]
def write(either: Either[A, B]) = format.write(either)
def read(value: JsValue) = format.read(value)
}
}
示例7: write
//设置package包名称以及导入依赖的类
package api.json
import core.model.{Account, AccountId}
import core.services.{AccountDTO, AccountsDTO}
import spray.json.{DefaultJsonProtocol, DeserializationException, JsString, JsValue, JsonFormat}
import squants.market.Money
trait AccountJsonProtocol {
this: DefaultJsonProtocol with CustomerJsonProtocol with CommonJsonProtocol =>
implicit val accountIdJsonFormat = new ModelEntityKeyJsonFormat[AccountId]
implicit val moneyJsonFormat = new JsonFormat[Money] {
def write(obj: Money): JsValue =
JsString(obj.toString())
def read(json: JsValue): Money = {
json match {
case JsString(str) =>
Money.apply(str).getOrElse(throw new DeserializationException("Failed to deserialize Money"))
case _ => throw new DeserializationException("Failed to deserialize Money")
}
}
}
import Account._
implicit val accountJsonFormat = jsonFormat(Account.apply, "id", "customerId", "balance")
implicit val accountDTOJsonFormat = jsonFormat2(AccountDTO.apply)
implicit val accountsDTOJsonFormat = jsonFormat1(AccountsDTO.apply)
}
示例8: VizRecJsonProtocol
//设置package包名称以及导入依赖的类
package com.lavsurgut.vizr.specs.vizrec
import spray.json.{DefaultJsonProtocol, DeserializationException, JsArray, JsObject, JsString, JsValue, JsonFormat, RootJsonFormat, _}
object VizRecJsonProtocol extends DefaultJsonProtocol {
implicit object FieldFormat extends JsonFormat[Field] {
def write(c: Field) =
JsObject(
Seq(
Some("channel" -> c.channel.toString.toJson),
Some("type" -> c.`type`.toString.toJson),
c.aggregate.map(aggregate => "aggregate" -> aggregate.toString.toJson),
c.field.map(field => "field" -> field.toJson),
c.timeUnit.map(timeUnit => "timeUnit" -> timeUnit.toString.toJson)
).flatten: _*
)
def read(value: JsValue) = {
value.asJsObject.getFields("channel", "type") match {
case Seq(JsString(channel), JsString(ttype)) =>
new Field(
channel = Channel.withName(channel),
`type` = Type.withName(ttype),
aggregate = value.asJsObject.fields.get("aggregate").map(v => Aggregate.withName(v.convertTo[String])),
field = value.asJsObject.fields.get("field").map(v => v.convertTo[String]),
timeUnit = value.asJsObject.fields.get("timeUnit").map(v => TimeUnit.withName(v.convertTo[String]))
)
case _ => throw new DeserializationException("Field spec expected")
}
}
}
implicit object VizRecSpecFormat extends RootJsonFormat[VizRecSpec] {
def write(c: VizRecSpec) = JsObject(
"mark" -> JsString(c.mark.toString),
"fields" -> JsArray(c.fields.map(f => FieldFormat.write(f)).toVector)
)
def read(value: JsValue) = {
value.asJsObject.getFields("mark", "fields") match {
case Seq(JsString(mark), JsArray(fields)) =>
new VizRecSpec(Mark.withName(mark), fields.map(f => FieldFormat.read(f)).toSeq)
case _ => throw new DeserializationException("VizRec spec expected")
}
}
}
}
示例9: write
//设置package包名称以及导入依赖的类
package csw.services.config.api.internal
import java.nio.file.{Path, Paths}
import java.time.Instant
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import csw.services.config.api.models.{ConfigFileInfo, ConfigFileRevision, ConfigId, ConfigMetadata}
import spray.json.{DefaultJsonProtocol, JsString, JsValue, JsonFormat, RootJsonFormat}
trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
implicit val fileFormat: JsonFormat[Path] = new JsonFormat[Path] {
override def write(obj: Path): JsValue = JsString(obj.toString)
override def read(json: JsValue): Path = json match {
case JsString(value) ? Paths.get(value)
case _ ? throw new RuntimeException("can not parse")
}
}
implicit val dateFormat: JsonFormat[Instant] = new JsonFormat[Instant] {
override def write(obj: Instant): JsValue = JsString(obj.toString)
override def read(json: JsValue): Instant = json match {
case JsString(value) ? Instant.parse(value)
case _ ? throw new RuntimeException("can not parse")
}
}
implicit val configIdFormat: RootJsonFormat[ConfigId] = jsonFormat1(new ConfigId(_))
implicit val configFileInfoFormat: RootJsonFormat[ConfigFileInfo] = jsonFormat3(ConfigFileInfo.apply)
implicit val configFileHistoryFormat: RootJsonFormat[ConfigFileRevision] = jsonFormat3(ConfigFileRevision.apply)
implicit val configMetadataFormat: RootJsonFormat[ConfigMetadata] = jsonFormat4(ConfigMetadata.apply)
}
示例10: Units
//设置package包名称以及导入依赖的类
package csw.units
import enumeratum.{Enum, EnumEntry}
import spray.json.JsonFormat
import scala.collection.immutable
sealed abstract class Units(name: String) extends EnumEntry with Serializable {
// Should parameterize Units so concat can be created concat[A, B]
override def toString: String = "[" + name + "]"
}
object Units extends Enum[Units] {
import csw.param.formats.JsonSupport._
override def values: immutable.IndexedSeq[Units] = findValues
implicit val format: JsonFormat[Units] = enumFormat(this)
object NoUnits extends Units("none")
object encoder extends Units("enc")
object micrometers extends Units("µm")
object millimeters extends Units("mm")
object meters extends Units("m")
object kilometers extends Units("km")
object degrees extends Units("deg")
object seconds extends Units("sec")
object milliseconds extends Units("ms")
}
示例11: Subsystem
//设置package包名称以及导入依赖的类
package csw.param.models
import enumeratum.EnumEntry.Lowercase
import enumeratum.{Enum, EnumEntry}
import spray.json.JsonFormat
import scala.collection.immutable
object Subsystem extends Enum[Subsystem] {
import csw.param.formats.JsonSupport._
override def values: immutable.IndexedSeq[Subsystem] = findValues
implicit val format: JsonFormat[Subsystem] = enumFormat(this)
case object AOESW extends Subsystem("AO Executive Software")
case object APS extends Subsystem("Alignment and Phasing System")
case object CIS extends Subsystem("Communications and Information Systems")
case object CSW extends Subsystem("Common Software")
case object DMS extends Subsystem("Data Management System")
case object DPS extends Subsystem("Data Processing System")
case object ENC extends Subsystem("Enclosure")
case object ESEN extends Subsystem("Engineering Sensor System")
case object ESW extends Subsystem("Executive Software System")
case object GMS extends Subsystem("Global Metrology System Controls")
case object IRIS extends Subsystem("InfraRed Imaging Spectrometer")
case object IRMS extends Subsystem("Infrared Multi-Slit Spectrometer")
case object LGSF extends Subsystem("Lasert Guide Star Facility")
case object M1CS extends Subsystem("M1 Control System")
case object M2CS extends Subsystem("M2 Control System")
case object M3CS extends Subsystem("M3 Control System")
case object MCS extends Subsystem("Mount Control System")
case object NFIRAOS extends Subsystem("Narrow Field Infrared AO System")
case object NSCU extends Subsystem("NFIRAOS Science Calibration Unit")
case object OSS extends Subsystem("Observatory Safety System")
case object PFCS extends Subsystem("Prime Focus Camera Controls")
case object PSFR extends Subsystem("NFIRAOS AO PSF Reconstructor")
case object RTC extends Subsystem("NFIRAOS Real-time Controller")
case object RPG extends Subsystem("NFIRAOS AO Reconstructor Parameter Generator")
case object SCMS extends Subsystem("Site Conditions Monitoring System")
case object SOSS extends Subsystem("Science Operations Support System")
case object STR extends Subsystem("Telescope Structure")
case object SUM extends Subsystem("Summit Facility")
case object TCS extends Subsystem("Telescope Control System")
case object TINC extends Subsystem("Prime Focus Camera Controls")
case object WFOS extends Subsystem("Wide Field Optical Spectrometer")
// for testing
case object TEST extends Subsystem("Testing System")
case object BAD extends Subsystem("Unknown/default Subsystem")
}
示例12:
//设置package包名称以及导入依赖的类
package csw.param.formats
import java.lang
import spray.json.{DefaultJsonProtocol, JsonFormat}
trait JavaFormats { self: DefaultJsonProtocol ?
//JSON Formats for Java by converting scala types to java types.
implicit val integerFormat: JsonFormat[Integer] = IntJsonFormat.asInstanceOf[JsonFormat[java.lang.Integer]]
implicit val booleanFormat: JsonFormat[lang.Boolean] = BooleanJsonFormat.asInstanceOf[JsonFormat[java.lang.Boolean]]
implicit val characterFormat: JsonFormat[lang.Character] =
CharJsonFormat.asInstanceOf[JsonFormat[java.lang.Character]]
implicit val shortFormat: JsonFormat[lang.Short] = ShortJsonFormat.asInstanceOf[JsonFormat[java.lang.Short]]
implicit val doubleFormat: JsonFormat[lang.Double] = DoubleJsonFormat.asInstanceOf[JsonFormat[java.lang.Double]]
implicit val floatFormat: JsonFormat[lang.Float] = FloatJsonFormat.asInstanceOf[JsonFormat[java.lang.Float]]
implicit val longFormat: JsonFormat[lang.Long] = LongJsonFormat.asInstanceOf[JsonFormat[java.lang.Long]]
implicit val byteFormat: JsonFormat[lang.Byte] = ByteJsonFormat.asInstanceOf[JsonFormat[java.lang.Byte]]
}
示例13: ResponseBuilder
//设置package包名称以及导入依赖的类
package homeworkzen.rest
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.{StatusCode, StatusCodes}
import akka.http.scaladsl.server.Directives.complete
import akka.http.scaladsl.server.StandardRoute
import homeworkzen.model._
import spray.json.{DefaultJsonProtocol, JsonFormat, RootJsonFormat}
object ResponseBuilder extends DefaultJsonProtocol with SprayJsonSupport {
private case class ResponseTemplateWithoutResult(statusCode: Int, message: String)
private case class ResponseTemplateWithResult[T](statusCode: Int, message: String, result: T)
private implicit val responseTemplateWithoutResultFormat: RootJsonFormat[ResponseTemplateWithoutResult] =
jsonFormat2(ResponseTemplateWithoutResult)
// same as akka http default
def internalServerError(): StandardRoute =
complete(StatusCodes.InternalServerError -> "There was an internal server error.")
def success(statusCode: StatusCode): StandardRoute =
complete(statusCode -> ResponseTemplateWithoutResult(statusCode.intValue, "success"))
def success[T](statusCode: StatusCode, result: T)(implicit jsonFormat: JsonFormat[T]): StandardRoute = {
implicit val format: RootJsonFormat[ResponseTemplateWithResult[T]] = jsonFormat3(ResponseTemplateWithResult[T])
complete(statusCode -> ResponseTemplateWithResult(statusCode.intValue, "success", result))
}
def failure(statusCode: StatusCode, message: String): StandardRoute =
complete(statusCode -> ResponseTemplateWithoutResult(statusCode.intValue, message))
def notFound(unitId: UnitId): StandardRoute = {
val body = ResponseTemplateWithoutResult(StatusCodes.NotFound.intValue, s"Could not find station with id ${unitId.id.toString}")
complete(StatusCodes.NotFound -> body)
}
}
示例14: SonicdSource
//设置package包名称以及导入依赖的类
package build.unstable.sonicd.source
import akka.actor.ActorContext
import build.unstable.sonic.model.{DataSource, Query, RequestContext}
import build.unstable.sonicd.SonicdLogging
import build.unstable.sonicd.source.SonicdSource._
import build.unstable.sonicd.system.actor.SonicdController._
import spray.json.JsonFormat
import build.unstable.sonic.JsonProtocol._
abstract class SonicdSource(query: Query, actorContext: ActorContext, context: RequestContext)
extends DataSource(query, actorContext, context) with SonicdLogging {
def getConfig[T: JsonFormat](key: String): T = {
val value = query.sonicdConfig.fields.get(key).flatMap(_.convertTo[Option[T]])
.getOrElse(throw new MissingConfigurationException(key))
log.debug("getConfig({})={}", key, value)
value
}
def getOption[T: JsonFormat](key: String): Option[T] = {
val value = query.sonicdConfig.fields.get(key).flatMap(_.convertTo[Option[T]])
log.debug("getOption({})={}", key, value)
value
}
}
object SonicdSource {
class MissingConfigurationException(missing: String) extends Exception(s"config is missing '$missing' field")
}
示例15: OrderStatusFormat
//设置package包名称以及导入依赖的类
package com.example
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import com.example.OrderActor._
import spray.json.{DefaultJsonProtocol, JsNull, JsString, JsValue, JsonFormat, RootJsonFormat}
trait OrderProtocols extends SprayJsonSupport with DefaultJsonProtocol {
implicit object OrderStatusFormat extends RootJsonFormat[OrderStatus] {
def write(status: OrderStatus) = JsString(status.name)
def read(value: JsValue): OrderStatus = value match {
case JsString(OrderStatus(s)) => s
case _ => throw new MatchError(s"not a valid OrderStatus $value")
}
}
implicit val priceFormat = jsonFormat2(Price)
implicit val productFormat = jsonFormat3(Product)
implicit val orderFormat = orderStatusDefaultJsonFormat(jsonFormat4(Order))
private def orderStatusDefaultJsonFormat[T](format: RootJsonFormat[T]): RootJsonFormat[T] = new RootJsonFormat[T] {
override def write(obj: T): JsValue = {
format.write(obj).asJsObject
}
override def read(json: JsValue): T = {
val order = json.asJsObject
format.read(order.fields.contains("orderStatus") match {
case true => order
case false => order.copy(fields = order.fields.updated("orderStatus", OrderStatusFormat.write(Open)))
})
}
}
}