本文整理汇总了Scala中spray.json.JsonFormat类的典型用法代码示例。如果您正苦于以下问题:Scala JsonFormat类的具体用法?Scala JsonFormat怎么用?Scala JsonFormat使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了JsonFormat类的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: 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.")
}
}
}
开发者ID:Morgan-Stanley,项目名称:proton,代码行数:60,代码来源:UsersProtocol.scala
示例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 {
}
开发者ID:TerriaJS,项目名称:magda,代码行数:59,代码来源:Model.scala
示例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'")
}
}
}
开发者ID:j5ik2o,项目名称:akka-ddd-cqrs-es-example,代码行数:34,代码来源:UUIDJsonProtocol.scala
示例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
开发者ID:cupenya,项目名称:authorization,代码行数:36,代码来源:ServiceUtils.scala
示例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)
}
}
开发者ID:Lastik,项目名称:money-transfer-sample,代码行数:52,代码来源:CommonJsonProtocol.scala
示例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)
}
开发者ID:Lastik,项目名称:money-transfer-sample,代码行数:34,代码来源:AccountJsonProtocol.scala
示例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")
}
}
}
}
开发者ID:lavsurgut,项目名称:vizr,代码行数:50,代码来源:VizRecJsonProtocol.scala
示例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)
}
开发者ID:tmtsoftware,项目名称:csw-prod,代码行数:36,代码来源:JsonSupport.scala
示例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")
}
开发者ID:tmtsoftware,项目名称:csw-prod,代码行数:30,代码来源:Units.scala
示例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")
}
开发者ID:tmtsoftware,项目名称:csw-prod,代码行数:52,代码来源:Subsystem.scala
示例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]]
}
开发者ID:tmtsoftware,项目名称:csw-prod,代码行数:19,代码来源:JavaFormats.scala
示例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)
}
}
开发者ID:anopse,项目名称:HomeworkZen,代码行数:39,代码来源:ResponseBuilder.scala
示例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")
}
开发者ID:ernestrc,项目名称:sonicd,代码行数:34,代码来源:SonicdSource.scala
示例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)))
})
}
}
}
开发者ID:mduesterhoeft,项目名称:order-akka,代码行数:36,代码来源:OrderProtocols.scala
示例16: Util
//设置package包名称以及导入依赖的类
import java.io.{ByteArrayOutputStream, FileInputStream}
import java.util.Properties
import org.apache.avro.io.EncoderFactory
import org.apache.avro.reflect.{ReflectData, ReflectDatumWriter}
import spray.json.JsonFormat
import scala.util.{Failure, Success, Try}
import spray.json.{JsonFormat, _}
import DefaultJsonProtocol._
object Util {
def parse[T](data: String)(implicit format : JsonFormat[T]) = {
Try {
val parsed = data.parseJson
parsed.convertTo[T]
}
}
def parseCollection[T](data: String)(implicit format : JsonFormat[T]) = {
Try {
val parsed = data.parseJson
parsed.convertTo[Seq[T]]
}
}
def serialize[T](obj: T) = {
val schema = ReflectData.get().getSchema(obj.getClass)
val writer = new ReflectDatumWriter[T](schema)
val out = new ByteArrayOutputStream
Try {
writer.write(obj, EncoderFactory.get.directBinaryEncoder(out, null))
out.toByteArray
}
}
def getFileLines(fileName : String) = scala.io.Source.fromFile(fileName).mkString.split("\n")
def loadPropertiesFile(fileName : String) = {
val prop = new Properties()
Try{
prop.load(new FileInputStream(fileName))
} match {
case Failure(e) => e.printStackTrace; System.exit(1)
case Success(msg) => ()
}
prop
}
}
开发者ID:msumner91,项目名称:FlinkCEP,代码行数:58,代码来源:Util.scala
示例17: Protocol
//设置package包名称以及导入依赖的类
package performanceanalysis.server
import performanceanalysis.server.Protocol._
import performanceanalysis.server.messages.AdministratorMessages.{RegisterComponent, RegisteredComponents}
import performanceanalysis.server.messages.AlertMessages.AllAlertRuleDetails
import performanceanalysis.server.messages.LogMessages.{Details, Log, Metric}
import performanceanalysis.server.messages.Rules
import spray.json.{DefaultJsonProtocol, JsString, JsValue, JsonFormat, _}
import scala.concurrent.duration.Duration
object Protocol {
case class ValueType(aType: Any)
}
trait Protocol extends DefaultJsonProtocol {
implicit object valueTypeFormat extends JsonFormat[ValueType] {
def read(value: JsValue): ValueType = value match {
case JsString("string") => ValueType(classOf[String])
case JsString("boolean") => ValueType(classOf[Boolean])
case JsString("duration") => ValueType(classOf[Duration])
case _ => deserializationError("Unknown value type")
}
def write(f: ValueType): JsValue = f.aType match {
case c if c == classOf[String] => JsString("string")
case c if c == classOf[Boolean] => JsString("boolean")
case c if c == classOf[Duration] => JsString("duration")
case _ => serializationError("Unknown value type")
}
}
implicit val metricFormatter = jsonFormat(Metric.apply, "metric-key", "regex", "value-type")
implicit val detailsFormatter = jsonFormat1(Details.apply)
implicit val registerComponentsFormatter = jsonFormat2(RegisterComponent.apply)
implicit val registeredComponentsFormatter = jsonFormat1(RegisteredComponents.apply)
implicit val thresholdRuleFormatter = jsonFormat1(Rules.Threshold.apply)
implicit val actionRuleFormatter = jsonFormat1(Rules.Action.apply)
implicit val alertingRuleFormatter = jsonFormat2(Rules.AlertRule.apply)
implicit val alertRulesDetailsFormatter = jsonFormat1(AllAlertRuleDetails.apply)
implicit val logFormatter = jsonFormat1(Log.apply)
}
开发者ID:scala-academy,项目名称:performance-analysis,代码行数:50,代码来源:Protocol.scala
示例18: Api
//设置package包名称以及导入依赖的类
package services
import akka.actor.ActorSystem
import spatutorial.shared.ImageJsonProtocol._
import spatutorial.shared.{Image, ImageStats}
import spray.client.pipelining._
import spray.http._
import spray.httpx.SprayJsonSupport._
import spray.json.{JsonFormat, _}
import scala.concurrent.Future
import scala.concurrent.duration._
object Api {
lazy val IN_DOCKER: Boolean = !System.getProperty("os.name").contains("Mac OS X")
val apiLocation = if (IN_DOCKER) {
"http://api:9000/api"
} else {
"http://localhost:9000/api"
}
val timeout = 5.seconds
//Spray needs an implicit ActorSystem and ExecutionContext
implicit val system = ActorSystem("apiClient")
import system.dispatcher
val logRequest: HttpRequest => HttpRequest = { r =>
println(r.toString); r
}
val logResponse: HttpResponse => HttpResponse = { r =>
println(r.toString); r
}
val pipeline: HttpRequest => Future[HttpResponse] = (
logRequest
~> sendReceive
~> logResponse
)
val pipelineToImage: HttpRequest => Future[List[Image]] = (
logRequest
~> sendReceive
~> logResponse
~> unmarshal[List[Image]]
)
def getUnderageImages: Future[List[Image]] = pipelineToImage(Get(s"$apiLocation/image/underage"))
def getImageStats: Future[ImageStats] = pipeline(Get(s"$apiLocation/image/stats")).map(response =>
implicitly[JsonFormat[ImageStats]].read(response.entity.asString.parseJson))
}
开发者ID:aphexcx,项目名称:iconoclast-webapp,代码行数:53,代码来源:Api.scala
示例19: RecentlyFilesHandler
//设置package包名称以及导入依赖的类
package de.thm.move.controllers
import java.nio.file.{Files, Path, StandardOpenOption}
import javafx.event.ActionEvent
import javafx.scene.control.MenuItem
import de.thm.move.Global
import de.thm.move.implicits.FxHandlerImplicits._
import de.thm.move.util.JFxUtils
import de.thm.recent._
import spray.json.JsonFormat
class RecentlyFilesHandler(recent:Recent[Path], pathClicked: Path => Unit) {
private def menuItem(path:Path): MenuItem = {
val item = new MenuItem(path.toString)
JFxUtils.addFontIcon(item, "\uf1c9")
item.setOnAction { _:ActionEvent =>
incrementPriorityOf(path)
println(recent.recentValuesByPriority)
pathClicked(path)
}
item
}
def incrementPriorityOf(path:Path): Unit =
recent.incrementPriority(path)
def getMenuItems:Seq[MenuItem] =
recent.recentElementsByPriority.map(menuItem)
def writeTo(outputFile:Path)(implicit pathFormat:JsonFormat[Path]): Unit = {
val jsonString = recent.toJson
Files.write(outputFile, jsonString.getBytes(Global.encoding))
}
}
开发者ID:THM-MoTE,项目名称:MoVE,代码行数:37,代码来源:RecentlyFilesHandler.scala
示例20: ServiceApi
//设置package包名称以及导入依赖的类
package com.github.cupenya.auth.service
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
开发者ID:cupenya,项目名称:auth-service,代码行数:36,代码来源:ServiceUtils.scala
注:本文中的spray.json.JsonFormat类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论