本文整理汇总了Scala中spray.json.RootJsonFormat类的典型用法代码示例。如果您正苦于以下问题:Scala RootJsonFormat类的具体用法?Scala RootJsonFormat怎么用?Scala RootJsonFormat使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了RootJsonFormat类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: DateJsonFormat
//设置package包名称以及导入依赖的类
package com.durooma.api.route
import java.sql.Date
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import com.durooma.api.model._
import com.durooma.db.Tables
import org.joda.time.DateTime
import org.joda.time.format.{DateTimeFormatter, ISODateTimeFormat}
import spray.json.{DefaultJsonProtocol, DeserializationException, JsString, JsValue, RootJsonFormat}
trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
implicit object DateJsonFormat extends RootJsonFormat[DateTime] {
private val parserISO : DateTimeFormatter = ISODateTimeFormat.dateTimeNoMillis()
override def write(obj: DateTime) = JsString(parserISO.print(obj))
override def read(json: JsValue) : DateTime = json match {
case JsString(s) => parserISO.parseDateTime(s)
case _ => throw DeserializationException("Invalid date format: " + json)
}
}
implicit object SqlDateJsonFormat extends RootJsonFormat[Date] {
override def write(obj: Date) = JsString(obj.toString)
override def read(json: JsValue) = json match {
case JsString(s) => Date.valueOf(s)
case _ => throw DeserializationException("Invalid date format: " + json)
}
}
implicit val userFormat = jsonFormat5(User.apply)
implicit val userRegistrationFormat = jsonFormat5(UserRegistration.apply)
implicit val accountFormat = jsonFormat4(Account.apply)
implicit val accounBodyFormat = jsonFormat2(AccountBody.apply)
implicit val labelFormat = jsonFormat3(Tables.LabelRow.apply)
implicit val transactionFormat = jsonFormat8(Transaction.apply)
implicit val transactionBodyFormat = jsonFormat7(TransactionBody.apply)
implicit val sessionFormat = jsonFormat3(Session.apply)
implicit val credentialsFormat = jsonFormat2(CustomCredentials.apply)
}
示例2: BooksFoundFormat
//设置package包名称以及导入依赖的类
package com.jjabuk.bookstore.catalog.protocols
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import com.jjabuk.bookstore.catalog.protocols.CatalogueProtocol.{Book, BookAdded, BooksFound}
import reactivemongo.bson.BSONObjectID
import spray.json.{DefaultJsonProtocol, JsArray, JsObject, JsString, JsValue, RootJsonFormat}
trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
implicit val BookAddedFormat = jsonFormat1(BookAdded.apply)
implicit object BooksFoundFormat extends RootJsonFormat[BooksFound] {
override def read(json: JsValue): BooksFound = ???
override def write(b: BooksFound): JsValue = JsObject(
"books" -> JsArray(b.books.map(book => BookFormat.write(book)).toVector)
)
}
implicit object BookFormat extends RootJsonFormat[Book] {
override def read(value: JsValue) = {
val uuid = fromField[Option[String]](value, "uuid")
val isbn = fromField[String](value, "isbn")
val title = fromField[String](value, "title")
val review = fromField[Option[String]](value, "review")
val publisher = fromField[Option[String]](value, "publisher")
Book(uuid.getOrElse(BSONObjectID.generate().stringify), isbn, title, review, publisher)
}
override def write(obj: Book): JsValue = JsObject(
"uuid" -> JsString(obj.uuid),
"isbn" -> JsString(obj.isbn),
"title" -> JsString(obj.title),
"review" -> JsString(obj.review.getOrElse("")),
"publisher" -> JsString(obj.publisher.getOrElse(""))
)
}
}
示例3: WebServerTest
//设置package包名称以及导入依赖的类
package wow.api
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import org.scalatest.{Ignore, Matchers, WordSpec}
import spray.json.DefaultJsonProtocol._
import spray.json.RootJsonFormat
import wow.auth.data.AccountAPI.AccountReq
import wow.utils.Reflection
@Ignore
class WebServerTest extends WordSpec with Matchers with ScalatestRouteTest {
Reflection.eagerLoadClasses()
implicit val userFormat: RootJsonFormat[AccountReq] = jsonFormat2(AccountReq.apply)
"The service" should {
"return a creation success code when an account is create" in {
Post("/account/create", AccountReq("myName", "myPass")) ~> WebServer.route ~> check {
status shouldEqual StatusCodes.Created
}
}
"return a success code when an account is deleted" in {
Post("/account/delete", "myName") ~> WebServer.route ~> check {
status shouldEqual StatusCodes.OK
}
}
"return a success code when a password is reinitialized" in {
Put("/account/reinitialize", AccountReq("myName", "myPass")) ~> WebServer.route ~> check {
status shouldEqual StatusCodes.OK
}
}
}
}
示例4: CoordinateFormat
//设置package包名称以及导入依赖的类
package model
import akka.http.scaladsl.unmarshalling.Unmarshaller
import base.CaseObjectSerializationSupport
import mapdomain.graph.Coordinate
import mapdomain.sidewalk.Ramp
import spray.json.{ DefaultJsonProtocol, DeserializationException, JsNumber, JsObject, JsString, JsValue, RootJsonFormat }
trait ModelFormatter extends DefaultJsonProtocol with CaseObjectSerializationSupport {
implicit object CoordinateFormat extends RootJsonFormat[Coordinate] {
def write(c: Coordinate) = JsObject(
"lat" -> JsNumber(c.latitude),
"lng" -> JsNumber(c.longitude))
def read(value: JsValue) = value.asJsObject.getFields("lat", "lng") match {
case Seq(JsNumber(latitude), JsNumber(longitude)) ?
Coordinate(latitude.toDouble, longitude.toDouble)
case _ ? throw DeserializationException("Coordinate expected")
}
}
implicit object PathCoordinateFormat extends RootJsonFormat[PathCoordinate] {
def write(pc: PathCoordinate) =
if (pc.street.isDefined)
JsObject(
"lat" -> JsNumber(pc.coordinate.latitude),
"lng" -> JsNumber(pc.coordinate.longitude),
"street" -> JsString(pc.street.get))
else
JsObject(
"lat" -> JsNumber(pc.coordinate.latitude),
"lng" -> JsNumber(pc.coordinate.longitude))
def read(value: JsValue) = value.asJsObject.getFields("lat", "lng", "street") match {
case Seq(JsNumber(latitude), JsNumber(longitude), JsString(street)) ?
PathCoordinate(Coordinate(latitude.toDouble, longitude.toDouble), Some(street))
case Seq(JsNumber(latitude), JsNumber(longitude)) ?
PathCoordinate(Coordinate(latitude.toDouble, longitude.toDouble))
case _ ? throw DeserializationException("PathCoordinate expected")
}
}
implicit val EdgeTypeFormat = caseObjectJsonFormat[EdgeType](StreetEdgeType, SidewalkEdgeType, StreetCrossingEdgeType)
implicit val VertexTypeFormat = caseObjectJsonFormat[VertexType](StreetVertexType, SidewalkVertexType)
implicit val ReportableElementTypeFormat = caseObjectJsonFormat[ReportableElementType](RAMP, SIDEWALK)
implicit val RampFormat = jsonFormat4(Ramp.apply)
implicit val EdgeFormat = jsonFormat4(Edge.apply)
implicit val VertexFormat = jsonFormat3(Vertex.apply)
implicit val MapContainerFormat = jsonFormat2(MapContainer.apply)
implicit val StreetFormat = jsonFormat3(Street.apply)
implicit val SidewalkFormat = jsonFormat2(Sidewalk.apply)
implicit val ReportableElementFormat = jsonFormat6(ReportableElement.apply)
implicit val StopFormat = jsonFormat4(Stop.apply)
implicit val PublicTransportPathFormat = jsonFormat4(PublicTransportPath)
implicit val StopCombinationFormat = jsonFormat6(PTCombination.apply)
implicit val EdgeTypeUnmarshaller = Unmarshaller.strict[String, EdgeType](EdgeTypeFormat.mapping)
}
示例5: caseJsonFormat
//设置package包名称以及导入依赖的类
package eu.shiftforward.apso.json
import eu.shiftforward.apso.collection.HMap
import spray.json.{ JsValue, RootJsonFormat }
import scala.collection.mutable.{ Map => MutableMap, ListBuffer }
import spray.json.DefaultJsonProtocol._
implicit def caseJsonFormat(implicit reg: JsonKeyRegistry) = new RootJsonFormat[JsonHMap] {
def read(json: JsValue): JsonHMap = {
val caseObj = JsonHMap()
json.asJsObject.fields.foreach {
case (k, v) =>
reg.keys.get(Symbol(k)) match {
case Some(caseKey) =>
caseObj.put(caseKey.toKey, caseKey.toValue(v))
case None =>
caseObj.put(new JsonHMapKey[JsValue](Symbol(k)) {}, v)
}
}
caseObj
}
def write(map: JsonHMap): JsValue = {
Map(map.map { entry =>
entry._1.sym.name -> entry._1.toJson(entry._2.asInstanceOf[entry._1.Value])
}: _*).toJson
}
}
}
示例6: PassengerInfoParser
//设置package包名称以及导入依赖的类
package parsing
import spray.http.DateTime
import spray.json.{RootJsonFormat, DefaultJsonProtocol}
import scala.util.Try
object PassengerInfoParser {
case class PassengerInfo(DocumentType: Option[String],
DocumentIssuingCountryCode: String, Age: Option[Int] = None)
case class PassengerInfoJson(DocumentType: Option[String],
DocumentIssuingCountryCode: String,
EEAFlag: String,
Age: Option[String] = None) {
def toPassengerInfo = PassengerInfo(DocumentType, DocumentIssuingCountryCode, Age match {
case Some(age) => Try(age.toInt).toOption
case None => None
})
}
object EventCodes {
val DoorsClosed = "DC"
val CheckIn = "CI"
}
case class VoyagePassengerInfo(EventCode: String,
ArrivalPortCode: String,
VoyageNumber: String,
CarrierCode: String,
ScheduledDateOfArrival: String,
ScheduledTimeOfArrival: String,
PassengerList: List[PassengerInfoJson]) {
def flightCode: String = CarrierCode + VoyageNumber
def scheduleArrivalDateTime: Option[DateTime] = {
DateTime.fromIsoDateTimeString(scheduleDateTimeString)
}
def passengerInfos: Seq[PassengerInfo] = PassengerList.map(_.toPassengerInfo)
private def scheduleDateTimeString: String = s"${ScheduledDateOfArrival}T${ScheduledTimeOfArrival}"
def summary: String = s"${ArrivalPortCode}/${CarrierCode}${VoyageNumber}@${scheduleDateTimeString}"
}
object FlightPassengerInfoProtocol extends DefaultJsonProtocol {
implicit val passengerInfoConverter = jsonFormat(PassengerInfoJson, "DocumentType",
"DocumentIssuingCountryCode", "NationalityCountryEEAFlag", "Age")
implicit val passengerInfoResponseConverter: RootJsonFormat[VoyagePassengerInfo] = jsonFormat7(VoyagePassengerInfo)
}
}
示例7: 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)
}
}
示例8: ModelEntityKeyJsonFormat
//设置package包名称以及导入依赖的类
package api
import core.model.ModelEntityKey
import spray.json.{DeserializationException, JsString, JsValue, RootJsonFormat}
package object json {
class ModelEntityKeyJsonFormat[T <: ModelEntityKey : Manifest] extends RootJsonFormat[T] {
def write(obj: T): JsValue = JsString(obj.id.toString)
def read(json: JsValue): T = json match {
case JsString(str) =>
manifest.runtimeClass.getConstructors()(0).newInstance(str).asInstanceOf[T]
case _ => throw new DeserializationException("ModelEntityKeyJsonFormat:read method: JsString expected")
}
}
}
示例9: FileBackedStatus
//设置package包名称以及导入依赖的类
package org.scalawag.jibe.backend
import java.io.File
import java.util.concurrent.atomic.AtomicReference
import java.util.function.UnaryOperator
import org.scalawag.jibe.FileUtils._
import spray.json.RootJsonFormat
class FileBackedStatus[A, B <: RootJsonFormat[A]](file: File, initialValue: A)(implicit jsonFormat: B) {
private[this] var _status: A = initialValue
updateFile(initialValue) // write the initial value to disk
def get: A = _status
def mutate(fn: A => A) = synchronized {
val oldValue = _status
val newValue = fn(_status)
if ( oldValue != newValue ) {
updateFile(newValue)
_status = newValue
// Fire a change event
changeListeners.get.foreach(_.apply(oldValue, newValue))
}
}
private[this] val changeListeners = new AtomicReference[Seq[(A, A) => Unit]](Seq.empty)
def addChangeListener(listener: (A, A) => Unit) =
changeListeners.getAndUpdate(new UnaryOperator[Seq[(A, A) => Unit]] {
override def apply(t: Seq[(A, A) => Unit]) = t :+ listener
})
private[this] def updateFile(a: A) =
writeFileWithPrintWriter(file) { pw =>
pw.print(jsonFormat.write(a).prettyPrint)
}
}
示例10: JsonFormat
//设置package包名称以及导入依赖的类
package org.scalawag.jibe.report
import spray.json.{JsString, JsValue, RootJsonFormat}
import spray.json._
import DefaultJsonProtocol._
object JsonFormat {
class EnumerationFormat[A](enum: Enumeration) extends RootJsonFormat[A] {
def write(obj: A): JsValue = JsString(obj.toString)
def read(json: JsValue): A = json match {
case JsString(str) => enum.withName(str).asInstanceOf[A]
case x => throw new RuntimeException(s"unknown enumeration value: $x")
}
}
implicit object mosFormat extends EnumerationFormat[ExecutiveStatus.Value](ExecutiveStatus)
implicit val mandateStatusFormat = jsonFormat9(MandateStatus.apply)
}
示例11: 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")
}
}
}
}
示例12: StandardJsonProtocol
//设置package包名称以及导入依赖的类
package io.clouderite.commons.scala.berries.json
import java.nio.file.{Path, Paths}
import java.time.Instant
import spray.json.{DeserializationException, JsFalse, JsNumber, JsString, JsTrue, JsValue, RootJsonFormat}
object StandardJsonProtocol {
implicit val instantJson = InstantJsonFormat
implicit val pathJson = PathJsonFormat
implicit val anyJson = PathJsonFormat
}
object InstantJsonFormat extends RootJsonFormat[Instant] {
def write(obj: Instant): JsValue = JsNumber(obj.toEpochMilli)
def read(json: JsValue): Instant = json match {
case JsNumber(number) => Instant.ofEpochMilli(number.toLong)
case _ => throw DeserializationException("JsNumber expected")
}
}
object PathJsonFormat extends RootJsonFormat[Path] {
def write(obj: Path): JsValue = JsString(obj.toString)
def read(json: JsValue): Path = json match {
case JsString(str) => Paths.get(str)
case _ => throw DeserializationException("JsString expected")
}
}
object AnyJsonFormat extends RootJsonFormat[Any] {
def write(x: Any): JsValue = x match {
case n: Int => JsNumber(n)
case n: Long => JsNumber(n)
case n: Double => JsNumber(n)
case n: BigDecimal => JsNumber(n)
case s: String => JsString(s)
case b: Boolean if b => JsTrue
case b: Boolean if !b => JsFalse
}
def read(value: JsValue): Any = value match {
case JsNumber(n) => n.doubleValue
case JsString(s) => s
case JsTrue => true
case JsFalse => false
}
}
示例13: SmtpApiJsonProtocol
//设置package包名称以及导入依赖的类
package org.miszkiewicz.model.json
import org.miszkiewicz.model.smtpapi.{SendAt, SendEachAt, SmtpApi}
import spray.json.{DefaultJsonProtocol, JsNumber, JsObject, JsValue, RootJsonFormat, _}
import scala.collection.mutable
object SmtpApiJsonProtocol extends DefaultJsonProtocol {
import FilterJsonProtocol._
import SendTimeJsonProtocol._
implicit object SmtpApiJsonFormat extends RootJsonFormat[SmtpApi] {
def write(c: SmtpApi) = {
val fields: mutable.MutableList[JsField] = mutable.MutableList()
if (c.recipients.nonEmpty) {
fields += ("to" -> c.recipients.toJson)
}
if (c.categories.nonEmpty) {
fields += ("category" -> c.categories.toJson)
}
if (c.uniqueArguments.nonEmpty) {
fields += ("unique_args" -> c.uniqueArguments.toJson)
}
if (c.sections.nonEmpty) {
fields += ("section" -> c.sections.toJson)
}
if (c.substitutions.nonEmpty) {
fields += ("sub" -> c.substitutions.toJson)
}
if (c.filters.nonEmpty) {
fields += ("filters" -> JsObject(c.filters.map(filter => filter.name -> filter.toJson): _*))
}
c.asmGroupId.foreach(asmGroupId => fields += ("asm_group_id" -> JsNumber(asmGroupId)))
c.scheduled.foreach(scheduled => fields += (scheduled.name -> scheduled.toJson))
JsObject(fields: _*)
}
def read(value: JsValue) = ???
}
}
示例14: 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)
}
示例15: write
//设置package包名称以及导入依赖的类
package csw.apps.clusterseed.admin.internal
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import csw.apps.clusterseed.commons.ClusterSeedLogger
import csw.services.logging.internal.LoggingLevels.Level
import csw.services.logging.models.LogMetadata
import spray.json.{DefaultJsonProtocol, JsString, JsValue, RootJsonFormat}
trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol with ClusterSeedLogger.Simple {
implicit val levelFormat: RootJsonFormat[Level] = new RootJsonFormat[Level] {
override def write(obj: Level): JsValue = JsString(obj.name)
override def read(json: JsValue): Level = json match {
case JsString(value) ? Level(value)
case _ ?
val runtimeException = new RuntimeException(s"can not parse $json")
log.error(runtimeException.getMessage, ex = runtimeException)
throw runtimeException
}
}
implicit val logMetadataFormat: RootJsonFormat[LogMetadata] = jsonFormat4(LogMetadata.apply)
}