• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala DefaultJsonProtocol类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中spray.json.DefaultJsonProtocol的典型用法代码示例。如果您正苦于以下问题:Scala DefaultJsonProtocol类的具体用法?Scala DefaultJsonProtocol怎么用?Scala DefaultJsonProtocol使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了DefaultJsonProtocol类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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")
      }
    }
  }
} 
开发者ID:abhinavrungta,项目名称:MineBitcoin,代码行数:59,代码来源:Formats.scala


示例2: 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)

} 
开发者ID:durooma,项目名称:api,代码行数:48,代码来源:JsonSupport.scala


示例3: Person

//设置package包名称以及导入依赖的类
package com.opalab.proto.models

import java.util.UUID

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import spray.json.DefaultJsonProtocol
import spray.json._

trait JsonSupportProtocols extends DefaultJsonProtocol with SprayJsonSupport {
  implicit val personProtocol = jsonFormat3(Person.apply)
}

case class Person(
                   first_name: String,
                   last_name: Option[String] = None,
                   var uuid: Option[String] = Some(UUID.randomUUID().toString)
                 ) {

  def asTuple = {
    this.uuid = Some(this.uuid.getOrElse(UUID.randomUUID().toString))
    this.uuid.get -> this
  }
}

object Person extends JsonSupportProtocols 
开发者ID:otobrglez,项目名称:proto,代码行数:26,代码来源:Person.scala


示例4:

//设置package包名称以及导入依赖的类
package com.shashank.akkahttp.project

import java.util.concurrent.ConcurrentHashMap

import akka.actor.ActorSystem
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import com.shashank.akkahttp.project.Models.{LoadRequest, ServiceJsonProtoocol}
import spray.json.JsArray

import scala.collection.JavaConverters._
import spray.json.{DefaultJsonProtocol, JsArray, pimpAny}
import spray.json.DefaultJsonProtocol._
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql._


trait RestService {
  implicit val system: ActorSystem
  implicit val materializer: ActorMaterializer
  implicit val sparkSession: SparkSession
  val datasetMap = new ConcurrentHashMap[String, Dataset[Row]]()

  import ServiceJsonProtoocol._

  val route =
    pathSingleSlash {
      get {
        complete {
          "welcome to rest service"
        }
      }
    } ~
      path("load") {
        post {
          entity(as[LoadRequest]) {
            loadRequest => complete {
              val id = "" + System.nanoTime()
              val dataset = sparkSession.read.format("csv")
                .option("header", "true")
                .load(loadRequest.path)
              datasetMap.put(id, dataset)
              id
            }
          }
        }
      } ~
      path("view" / """[\w[0-9]-_]+""".r) { id =>
        get {
          complete {
            val dataset = datasetMap.get(id)
            dataset.take(10).map(row => row.toString())
          }
        }
      }
} 
开发者ID:shashankgowdal,项目名称:introduction-to-akkahttp,代码行数:58,代码来源:RestService.scala


示例5: 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(""))
    )
  }
} 
开发者ID:jjabuk,项目名称:bookstore,代码行数:39,代码来源:JsonSupport.scala


示例6: AppConfig

//设置package包名称以及导入依赖的类
package routing

import com.typesafe.config.ConfigFactory
import spray.json.DefaultJsonProtocol

case class AppConfig(googleClientId: String)

import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._

class AppConfigRouting extends DefaultJsonProtocol {
  implicit val appConfigFormat = jsonFormat1(AppConfig)
  val config                   = ConfigFactory.load()

  val routes = path("config") {
    get {
      complete(OK -> AppConfig(googleClientId = config.getString("googleClientId")))
    }
  }
} 
开发者ID:Leonti,项目名称:receipts-rest-service,代码行数:22,代码来源:AppConfigRouting.scala


示例7: DocumentService

//设置package包名称以及导入依赖的类
package service.documents

import javax.inject.{Inject, Named}

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.server.Directives._
import spray.json.DefaultJsonProtocol




@Named
class DocumentService @Inject()(documentRepository: DocumentRepository) extends DefaultJsonProtocol with SprayJsonSupport {

  val docRoutes =
    path("documents") {
      get {
        complete(documentRepository.getDocuments)
      }
    } ~
      path("document"/Segment  ) {
        r => complete(documentRepository.getDocument(r))
      } ~
      path("nowatermarks") {
        complete(documentRepository.getNoWatermarks)
      } ~
      path("nowatermark"/"""\w+""".r) {
        r => complete(documentRepository.getNoWatermark(r))
      }

} 
开发者ID:devknutst,项目名称:watermarkAkka,代码行数:32,代码来源:DocumentService.scala


示例8: MyJsonProtocol

//设置package包名称以及导入依赖的类
package com.datamountaineer.connect.tools

import spray.json.DefaultJsonProtocol


object MyJsonProtocol extends DefaultJsonProtocol {
  implicit val task = jsonFormat2(Task)
  implicit val connectorinfo = jsonFormat3(ConnectorInfo)
  implicit val tasklessconnectorinfo = jsonFormat2(TasklessConnectorInfo)
  implicit val errormsg = jsonFormat2(ErrorMessage)
  implicit val connectorstatus = jsonFormat3(ConnectorStatus)
  implicit val taskstatus = jsonFormat4(TaskStatus)
  implicit val connectortaskstatus = jsonFormat3(ConnectorTaskStatus)
  implicit val connectorplugins = jsonFormat1(ConnectorPlugins)
  implicit val values = jsonFormat5(Values)
  implicit val definitions = jsonFormat9(Definition)
  implicit val configs = jsonFormat2(Configs)
  implicit val connectorpluginsvalidate = jsonFormat4(ConnectorPluginsValidate)
} 
开发者ID:datamountaineer,项目名称:kafka-connect-tools,代码行数:20,代码来源:Domain.scala


示例9: HealthCheckModel

//设置package包名称以及导入依赖的类
package com.github.cupenya.hello

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.server.Directives
import akka.http.scaladsl.model.StatusCodes._
import spray.json.DefaultJsonProtocol

sealed trait HealthCheckModel

object HealthCheckModel extends DefaultJsonProtocol {
  implicit val healthCheckResultFormat = jsonFormat2(HealthCheckResult)
}

case class HealthCheckResult(name: String, status: String) extends HealthCheckModel

trait HealthHttpService extends Directives with SprayJsonSupport with Protocols with Logging {
  val healthRoute =
    pathPrefix("health") {
      get {
        complete(OK -> Map(
          "services" -> List(
            HealthCheckResult("service1", "ok")
          )
        ))
      }
    }
} 
开发者ID:cupenya,项目名称:hello-world-microservice,代码行数:28,代码来源:HealthHttpService.scala


示例10: 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 {
  
} 
开发者ID:TerriaJS,项目名称:magda,代码行数:59,代码来源:Model.scala


示例11: 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'")
    }

  }

} 
开发者ID:j5ik2o,项目名称:akka-ddd-cqrs-es-example,代码行数:34,代码来源:UUIDJsonProtocol.scala


示例12: Event

//设置package包名称以及导入依赖的类
package fraud.main

import org.apache.spark.mllib.linalg.Vectors
import spray.json.DefaultJsonProtocol
import java.util.UUID._

case class Event(id: String, user: String, item: String, action: String, timestamp: String)

object EventJsonProtocol extends DefaultJsonProtocol {
  implicit val EventFormat = jsonFormat5(Event)
}

object Domain {
  val items = Seq("Toy Banner", "Suit Banner", "Skirt Banner")
  val itemIds = Map(items(0) -> 0, items(1) -> 1, items(2) -> 2)
  
  val actions = Seq("Click", "View", "Loaded")
  
  val users = Seq("Billy", "John", "Mary")
  val userIds = Map(users(0) -> 0, users(1) -> 1, users(2) -> 2)
  
  def features(e: Event) = Vectors.dense(itemId(e), userId(e))
  def itemId(e: Event): Int = itemIds(e.item)
  def userId(e: Event): Int = userIds(e.user)
}

object RandomEvent {
  val rnd = new scala.util.Random()
  def randomFraudEvent() = Event(randomUUID.toString, Domain.users(0).toString, Domain.items(1), Domain.actions(0), timestamp)
  //Constructs a random events
  def apply(): Event = Event(randomUUID.toString, randomUser, randomItem, randomAction, timestamp)
  def randomItem() = Domain.items(rnd.nextInt(Domain.items.size))
  def randomUser() = Domain.users(rnd.nextInt(Domain.users.size))
  def randomAction() = Domain.actions(rnd.nextInt(Domain.actions.size))
  def timestamp() = new java.util.Date().toString()
} 
开发者ID:bbiletskyy,项目名称:fraud-dm,代码行数:37,代码来源:Domain.scala


示例13: ICSModel

//设置package包名称以及导入依赖的类
package com.pacbio.simulator

import java.util.UUID

import com.pacbio.common.models.UUIDJsonProtocol
import spray.json.DefaultJsonProtocol


object ICSModel {

  case class RunObj(dataModel :String, uniqueId : UUID, summary : String)
  case class ICSRun(startedby : String, run : RunObj)

  case class RunResponse(createdAt : Option[String]=null,
                        createdBy : Option[String]=null,
                        dataModel: String,
                        instrumentSerialNumber : Option[String]=null,
                        name : String,
                        reserved : Boolean,
                        status: Int,
                        summary:String,
                        totalCells : Int,
                        uniqueId : Option[String] = null)

  //NOTE : this is just a subset of InstrumentState elements. We do not need to deserialize the entire json
  case class InstrumentState (runState : Int, state : Int)

  // NOTE : this is just a subset of RunRequirements elements. We do not need to deserialize the entire json
  case class RunRequirements (hasSufficientInventory : Boolean, hasValidDataTransferLocations : Boolean)
}

trait ICSJsonProtocol extends DefaultJsonProtocol with UUIDJsonProtocol{
  import ICSModel._

  implicit val runObjF = jsonFormat3(RunObj)
  implicit val icsRunF = jsonFormat2(ICSRun)
  implicit val icsRunGetF = jsonFormat10(RunResponse)
  implicit val instrumentStateF = jsonFormat2(InstrumentState)
  implicit val runRequirementsFF = jsonFormat2(RunRequirements)
}

object ICSJsonProtocol extends ICSJsonProtocol 
开发者ID:PacificBiosciences,项目名称:smrtflow,代码行数:43,代码来源:IcsClientModel.scala


示例14: BackendJsonProtocol

//设置package包名称以及导入依赖的类
package org.breakout.connector.backend

import akka.actor.ActorSystem
import com.typesafe.config.ConfigFactory
import com.typesafe.scalalogging.Logger
import org.breakout.connector.HttpConnection._
import org.breakout.connector.backend.BackendRoutes.ADD_PAYMENT
import spray.client.pipelining._
import spray.http._
import spray.httpx.SprayJsonSupport._
import spray.json.{DefaultJsonProtocol, NullOptions}

import scala.concurrent.Future

object BackendJsonProtocol extends DefaultJsonProtocol with NullOptions {
  implicit val backendPaymentFormat = jsonFormat2(BackendPayment)
  implicit val backendInvoiceFormat = jsonFormat2(BackendInvoice)
}

case class BackendRoute(url: String)

object BackendRoutes {

  private val config = ConfigFactory.load()
  private val baseUrl = config.getString("backend.url")

  def ADD_PAYMENT(purposeOfTransferCode: String): BackendRoute =
    BackendRoute(s"$baseUrl/invoice/payment/$purposeOfTransferCode/")
}

object BackendApi {

  private val log = Logger[BackendApi.type]
  private val config = ConfigFactory.load()
  private val authToken = config.getString("backend.authToken")
  private implicit val system = ActorSystem()

  import BackendJsonProtocol._
  import system.dispatcher

  private val backendPipeline = (
    addHeader("X-AUTH-TOKEN", authToken)
      // ~> logReq
      ~> sendReceive
      // ~> logResp
      ~> setContentType(MediaTypes.`application/json`)
    )

  def addPayment(purposeOfTransferCode: String, payment: BackendPayment): Future[BackendInvoice] = {
    log.debug(s"adding Payment $purposeOfTransferCode; $payment")
    val pipeline = backendPipeline ~> unmarshal[BackendInvoice]
    pipeline(Post(ADD_PAYMENT(purposeOfTransferCode).url, payment))
  }

} 
开发者ID:BreakOutEvent,项目名称:breakout-payment,代码行数:56,代码来源:BackendApi.scala


示例15: Person

//设置package包名称以及导入依赖的类
package com.sky.workshop.spray

import spray.routing.HttpService
import spray.http.MediaTypes._

import spray.json.DefaultJsonProtocol
import spray.httpx.unmarshalling._
import spray.httpx.marshalling._

case class Person(title: String, forename: String, surname: String)

object PersonJsonProtocol extends DefaultJsonProtocol {
  implicit val PersonJF = jsonFormat3(Person)
}

import PersonJsonProtocol._
import spray.httpx.SprayJsonSupport._

trait PersonService extends HttpService {
  val personRoutes =
    path("person") {
      get {
        respondWithMediaType(`application/json`) {
          complete {
            Person("Mr", "Bobby", "Bobbyson")
          }
        }
      }
    }
} 
开发者ID:peteslater-sky,项目名称:SprayWorkshop,代码行数:31,代码来源:PersonService.scala


示例16: 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)
} 
开发者ID:cspinetta,项目名称:footpath-routing,代码行数:60,代码来源:ModelFormatter.scala


示例17: 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)
  }

} 
开发者ID:UKHomeOffice,项目名称:drt-passenger-splits,代码行数:52,代码来源:PassengerInfoParser.scala


示例18: AccountRestService

//设置package包名称以及导入依赖的类
package api

import akka.actor.ActorSystem
import akka.pattern.ask
import api.json.{AccountJsonProtocol, CommonJsonProtocol, CustomerJsonProtocol}
import common.{ErrorMessage, ServiceSuccess}
import core.model.{Account, AccountId}
import core.services._
import spray.json.DefaultJsonProtocol
import spray.routing.Directives
import spray.httpx.SprayJsonSupport._

import scala.concurrent.ExecutionContext

class AccountRestService(implicit executionContext: ExecutionContext, implicit val system: ActorSystem) extends RestServiceBase
  with Directives with DefaultJsonProtocol with CommonJsonProtocol with CustomerJsonProtocol with AccountJsonProtocol {

  val customerService = lookup(CustomerService.Id)
  val accountService = lookup(AccountService.Id)

  val route =
    pathPrefix("accounts") {
      path(JavaUUID) {
        accountId =>
          get {
            onComplete(accountService.ask(AccountService.FindAccountById(accountId)).mapTo[Either[ErrorMessage, ServiceSuccess[Account]]]) {
              case scala.util.Success(res) => complete(res)
              case scala.util.Failure(ex) => failWith(ex)
            }
          }
      } ~
        pathEnd {
          post {
            entity(as[AccountDTO]) { accountDTO =>
              onComplete(accountService.ask(AccountService.CreateAccount(accountDTO)).mapTo[Either[ErrorMessage, ServiceSuccess[AccountId]]]) {
                case scala.util.Success(res) => complete(res)
                case scala.util.Failure(ex) => failWith(ex)
              }
            }
          }
        }
    }
} 
开发者ID:Lastik,项目名称:money-transfer-sample,代码行数:44,代码来源:AccountRestService.scala


示例19: TransactionRestService

//设置package包名称以及导入依赖的类
package api

import akka.actor.ActorSystem
import akka.pattern.ask
import api.json.{AccountJsonProtocol, CommonJsonProtocol, CustomerJsonProtocol, TransactionJsonProtocol}
import common.{ErrorMessage, ServiceSuccess}
import core.model.Transaction
import core.services._
import spray.httpx.SprayJsonSupport._
import spray.json.DefaultJsonProtocol
import spray.routing.Directives

import scala.concurrent.ExecutionContext

class TransactionRestService(implicit executionContext: ExecutionContext, implicit val system: ActorSystem) extends RestServiceBase
  with Directives with DefaultJsonProtocol with CommonJsonProtocol with AccountJsonProtocol with CustomerJsonProtocol with TransactionJsonProtocol {

  val transactionService = lookup(TransactionService.Id)

  val route =
    pathPrefix("transaction" / "process") {
      pathEnd {
        post(entity(as[Transaction]) { transaction =>
          onComplete(transactionService.ask(TransactionService.ProcessTransaction(transaction)).mapTo[Either[ErrorMessage, ServiceSuccess[String]]]) {
            case scala.util.Success(res) => complete(res)
            case scala.util.Failure(ex) => failWith(ex)
          }
        })
      }
    }
} 
开发者ID:Lastik,项目名称:money-transfer-sample,代码行数:32,代码来源:TransactionRestService.scala


示例20: CustomerRestService

//设置package包名称以及导入依赖的类
package api

import akka.actor.ActorSystem
import akka.pattern.ask
import api.json.{AccountJsonProtocol, CommonJsonProtocol, CustomerJsonProtocol}
import common.{ErrorMessage, ServiceSuccess}
import core.model.{Account, CustomerId}
import core.services._
import spray.json.DefaultJsonProtocol
import spray.routing.Directives
import spray.httpx.SprayJsonSupport._

import scala.concurrent.ExecutionContext

class CustomerRestService(implicit executionContext: ExecutionContext, implicit val system: ActorSystem) extends RestServiceBase
  with Directives with DefaultJsonProtocol with CommonJsonProtocol with CustomerJsonProtocol with AccountJsonProtocol {

  val customerService = lookup(CustomerService.Id)
  val accountService = lookup(AccountService.Id)

  val route =
    pathPrefix("customers") {
      pathEnd {
        get {
          onComplete(customerService.ask(CustomerService.GetAllCustomers()).mapTo[CustomersDTO]) {
            case scala.util.Success(res) => complete(res)
            case scala.util.Failure(ex) => failWith(ex)
          }
        } ~
          post(entity(as[CustomerCreateDTO]) { customerDTO =>
            onComplete(customerService.ask(CustomerService.CreateCustomer(customerDTO)).mapTo[CustomerId]) {
              case scala.util.Success(res) => complete(res)
              case scala.util.Failure(ex) => failWith(ex)
            }
          })
      } ~
        pathPrefix(JavaUUID / "accounts") {
          customerId =>
            pathEnd {
              get {
                onComplete(accountService.ask(AccountService.FindCustomerAccounts(customerId)).mapTo[Either[ErrorMessage, ServiceSuccess[AccountsDTO]]]) {
                  case scala.util.Success(res) => complete(res)
                  case scala.util.Failure(ex) => failWith(ex)
                }
              }
            }
        }
    }
} 
开发者ID:Lastik,项目名称:money-transfer-sample,代码行数:50,代码来源:CustomerRestService.scala



注:本文中的spray.json.DefaultJsonProtocol类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala GuiceApplicationBuilder类代码示例发布时间:2022-05-23
下一篇:
Scala TestProbe类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap