当前位置: 首页>>代码示例>>Scala>>正文


Scala DefaultJsonProtocol类代码示例

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


在下文中一共展示了DefaultJsonProtocol类的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")
      }
    }
  }
} 
开发者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


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