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

Scala _类代码示例

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

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



在下文中一共展示了_类的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: 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


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


示例3: 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) = ???
  }

} 
开发者ID:dmiszkiewicz,项目名称:sendgrid-scala,代码行数:43,代码来源:SmtpApiJsonProtocol.scala


示例4: AuthTokenFormat

//设置package包名称以及导入依赖的类
package rest.client.support

import authentication.entities.{AuthToken, BearerToken}
import spray.json.{JsString, _}
import support.JsonApiSupport

trait JsonSupport extends JsonApiSupport {

  implicit object AuthTokenFormat extends RootJsonFormat[AuthToken] {
    override def read(json: JsValue): AuthToken = json match {
      case jsObject: JsObject =>
        jsObject.getFields("bearer") match {
          case Seq(JsString(bearer)) => BearerToken(bearer)
        }
      case _ => deserializationError("An error occurred while deserialize entity.")
    }

    override def write(obj: AuthToken): JsValue = obj match {
      case _ => deserializationError("Operation not supported.")
    }
  }
} 
开发者ID:lymr,项目名称:fun-chat,代码行数:23,代码来源:JsonSupport.scala


示例5: DiscriminatedJsonFormat

//设置package包名称以及导入依赖的类
package de.choffmeister.microserviceutils.json

import spray.json.{JsObject, JsString, _}

import scala.reflect.ClassTag

object DiscriminatedJsonFormat {
  def apply[T](discriminator: String): DiscriminatedJsonFormat[T] =
    new BaseDiscriminatedJsonFormat[T](discriminator)
}


sealed trait DiscriminatedJsonFormat[T] {
  val discriminator: String
  def format: RootJsonFormat[T]

  def extend[T2 <: T](`type`: String)(implicit f: RootJsonFormat[T2], c: ClassTag[T2]): DiscriminatedJsonFormat[T] =
    new ExtendedDiscriminatedJsonFormat[T, T2](this, discriminator, `type`)
}

private[json] final class BaseDiscriminatedJsonFormat[T](val discriminator: String) extends DiscriminatedJsonFormat[T] {
  override def format = new RootJsonFormat[T] {
    override def write(obj: T) = throw new SerializationException("Missing serializer for given JSON")

    override def read(json: JsValue) = throw DeserializationException("Missing deserializer for given JSON")
  }
}

private[json] final class ExtendedDiscriminatedJsonFormat[T, T2 <: T](base: DiscriminatedJsonFormat[T], val discriminator: String, `type`: String)(implicit f: RootJsonFormat[T2], c: ClassTag[T2]) extends DiscriminatedJsonFormat[T] {
  override def format: RootJsonFormat[T] = new RootJsonFormat[T] {
    override def write(obj: T): JsValue =
      obj match {
        case o: T2 => JsObject(f.write(o).asJsObject.fields + (discriminator -> JsString(`type`)))
        case _ => base.format.write(obj)
      }

    override def read(json: JsValue): T =
      json.asJsObject.getFields(discriminator) match {
        case Seq(JsString(`type`)) => f.read(json)
        case _ => base.format.read(json)
      }
  }
} 
开发者ID:choffmeister,项目名称:microservice-utils,代码行数:44,代码来源:DiscriminatedJsonFormat.scala


示例6: 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


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


示例8: 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


示例9: JLongFormat

//设置package包名称以及导入依赖的类
package com.ntsdev.http.marshalling

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import com.ntsdev.domain.Person
import spray.json.{JsonFormat, _}

import scala.collection.JavaConversions._

trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
  implicit object JLongFormat extends JsonFormat[java.lang.Long]{
    def write(obj: java.lang.Long) = JsNumber(obj)
    def read(json: JsValue) : java.lang.Long = json match {
      case JsNumber(value: BigDecimal) => value.longValue()
      case x => deserializationError("Expected Long as BigDecimal, but got " + x)
    }
  }

  implicit object jSetPersonFormat extends JsonFormat[java.util.Set[Person]] {
    def write(set: java.util.Set[Person]) = JsArray(set.toSet.map((value: Person) => value.toJson).toVector)
    def read(json: JsValue) = json match {
      case JsArray(elements) => elements.map(_.convertTo[Person]).toSet[Person]
      case x => deserializationError("Expected Set as JsArray, but got " + x)
    }
  }

  implicit val personFormat: JsonFormat[Person] = lazyFormat(
    jsonFormat(Person, "id", "firstName", "lastName", "twitter_id", "contacts")
  )
} 
开发者ID:neilshannon,项目名称:atlanta-scala-microservice,代码行数:30,代码来源:JsonSupport.scala


示例10: ActionsSpec

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

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import mm4s.api.ActionProtocol._
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpec}
import spray.json.{DefaultJsonProtocol, _}


class ActionsSpec extends WordSpec with Matchers with BeforeAndAfterAll with DefaultJsonProtocol {

  "protocol" should {
    Actions.list().map(ActionContainer).foreach { c =>
      s"serialize ${c.action.key}" in {
        c.toJson shouldBe s"""{"action":"${c.action.key}"}""".parseJson
      }
    }
  }

  case class ActionContainer(action: Action)
  implicit val actionContainerFormat: RootJsonFormat[ActionContainer] = jsonFormat1(ActionContainer)
} 
开发者ID:jw3,项目名称:mm4s,代码行数:23,代码来源:ActionsSpec.scala


示例11: GameData

//设置package包名称以及导入依赖的类
package eu.reactivesystems.league.impl

import eu.reactivesystems.league.api.Game
import spray.json.{JsValue, _}

case class GameData(home: ClubData, away: ClubData)(val round: Int,
                                                    val homeGoals: Int,
                                                    val awayGoals: Int)

object GameData {
  def apply(game: Game) =
    new GameData(ClubData(game.home), ClubData(game.away))(game.round,
                                                           game.homeGoals,
                                                           game.awayGoals)

  implicit object GameDataFormat extends RootJsonFormat[GameData] {
    def write(g: GameData) = JsObject(
      "home" -> g.home.toJson,
      "away" -> g.away.toJson,
      "round" -> JsNumber(g.round),
      "homeGoals" -> JsNumber(g.homeGoals),
      "awayGoals" -> JsNumber(g.awayGoals)
    )
    def read(value: JsValue) = {
      value.asJsObject.getFields("home",
                                 "away",
                                 "round",
                                 "homeGoals",
                                 "awayGoals") match {
        case Seq(home @ JsObject(_),
                 away @ JsObject(_),
                 JsNumber(round),
                 JsNumber(homeGoals),
                 JsNumber(awayGoals)) =>
          new GameData(home.convertTo[ClubData], away.convertTo[ClubData])(
            round.toInt,
            homeGoals.toInt,
            awayGoals.toInt)
        case _ => throw new DeserializationException("Color expected")
      }
    }
  }
} 
开发者ID:reactivesystems-eu,项目名称:eventsourcing-intro,代码行数:44,代码来源:GameData.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala EitherT类代码示例发布时间:2022-05-23
下一篇:
Scala DistributedPubSub类代码示例发布时间: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