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


Scala JsObject类代码示例

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


在下文中一共展示了JsObject类的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: 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

示例3: fieldName

//设置package包名称以及导入依赖的类
package net.ruippeixotog.scalafbp.protocol.message

import fommil.sjs._
import shapeless.Typeable
import spray.json.{ JsObject, JsString }

trait CustomJsonFormatHints extends JsonFormatHints {

  trait LowerCaseHints[T] extends CoproductHint[T] {
    override protected def fieldName(orig: String) = orig.toLowerCase
  }

  class MessageCoproductHint(protocolKey: String, commandKey: String, payloadKey: String)(implicit t: Typeable[ProtocolWrapper])
      extends CoproductHint[ProtocolWrapper] with LowerCaseHints[ProtocolWrapper] {

    def read[Name <: Symbol](j: JsObject, n: Name): Option[JsObject] = {
      j.fields.get(protocolKey) match {
        case Some(JsString(hint)) if hint == fieldName(n.name) =>
          j.fields.get(payloadKey) match {
            case Some(obj: JsObject) =>
              j.fields.get(commandKey) match {
                case Some(cmd) => Some(JsObject(payloadKey -> JsObject(obj.fields + (commandKey -> cmd))))
                case None => deserError(s"missing $commandKey, found ${j.fields.keys.mkString(",")}")
              }
            case Some(js) =>
              j.fields.get(commandKey) match {
                case Some(cmd) => Some(JsObject(payloadKey -> JsObject("_value" -> js, commandKey -> cmd)))
                case None => deserError(s"missing $commandKey, found ${j.fields.keys.mkString(",")}")
              }
            case None => deserError(s"missing $payloadKey, found ${j.fields.keys.mkString(",")}")
          }
        case Some(JsString(hint)) => None
        case _ => deserError(s"missing $commandKey, found ${j.fields.keys.mkString(",")}")
      }
    }

    def write[Name <: Symbol](j: JsObject, n: Name): JsObject = {
      val payloadJson = j.fields(payloadKey).asJsObject
      val payloadValue = payloadJson.fields.getOrElse("_value", JsObject(payloadJson.fields - commandKey))
      JsObject(
        protocolKey -> JsString(fieldName(n.name)),
        commandKey -> payloadJson.fields(commandKey),
        payloadKey -> payloadValue)
    }
  }

  implicit override def coproductHint[T: Typeable] =
    new FlatCoproductHint[T]("command") with LowerCaseHints[T]
}

object CustomJsonFormatHints extends CustomJsonFormatHints 
开发者ID:ruippeixotog,项目名称:scalafbp,代码行数:52,代码来源:CustomJsonFormatHints.scala

示例4: Implicits

//设置package包名称以及导入依赖的类
package ru.fediq.scrapingkit.util

import spray.json.JsObject

import scala.concurrent.{ExecutionContext, Future}

object Implicits {
  implicit class StringToAnyMapWrapper(val map: Map[String, Any]) extends AnyVal {
    def mapToJson: JsObject = Utilities.mapToJson(map)
  }

  implicit class SequenceWrapper[A](val seq: Seq[A]) extends AnyVal {
    def foldFutures[B](z: B)(f: (B, A) => Future[B])(implicit ec: ExecutionContext): Future[B] = {
      var future: Future[B] = Future.successful(z)
      for (a: A <- seq) {
        future = future.flatMap(b => f(b, a))
      }
      future
    }

    def chainFutures(f: A => Future[_])(implicit ec: ExecutionContext): Future[_] = {
      foldFutures(AnyRef.asInstanceOf[Any])((_, a) => f(a))
    }
  }
} 
开发者ID:fediq,项目名称:scraping-kit,代码行数:26,代码来源:Implicits.scala

示例5: Status

//设置package包名称以及导入依赖的类
// Copyright (c) Microsoft.All rights reserved.

package com.microsoft.azure.iot.iothub2cassandra.webservice

import java.lang.management.ManagementFactory

import spray.json.{JsNumber, JsObject, JsString, JsValue}

object Status {
  def get: JsValue = {
    val runtimeMXB = ManagementFactory.getRuntimeMXBean
    val osMXB = ManagementFactory.getOperatingSystemMXBean

    val runtime = JsObject(
      "startTime" ? JsNumber(runtimeMXB.getStartTime),
      "uptimeMsecs" ? JsNumber(runtimeMXB.getUptime),
      "name" ? JsString(runtimeMXB.getName),
      "vmName" ? JsString(runtimeMXB.getVmName)
    )

    val os = JsObject(
      "arch" ? JsString(osMXB.getArch),
      "name" ? JsString(osMXB.getName),
      "version" ? JsString(osMXB.getVersion),
      "processors" ? JsNumber(osMXB.getAvailableProcessors),
      "systemLoadAvg" ? JsNumber(osMXB.getSystemLoadAverage)
    )

    JsObject(
      "runtime" ? runtime,
      "os" ? os
    )
  }
} 
开发者ID:Azure,项目名称:toketi-iothub-to-cassandra,代码行数:35,代码来源:Status.scala

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

示例7: registerUserRoute

//设置package包名称以及导入依赖的类
package io.scalac.wtf.domain

import akka.http.scaladsl.server.Directives._
import cats.data.{Reader, Xor}
import spray.json.{JsObject, JsString}

import UserService.createUser
import spray.json.DefaultJsonProtocol._
import cats.implicits._
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._

trait UserRoutes {
  implicit val userFormat = jsonFormat2(NewUser)

  def registerUserRoute = Reader((config: Config) => {
    implicit val ec = config.ec
    path("register") {
      post {
        entity(as[NewUser]) { userRequest =>
          val user = User(email = userRequest.email, password = userRequest.password)
          val result = config.db.run(createUser(user))

          complete {
            result.map {
              case Xor.Left(errors) => JsString(errors.unwrap.mkString(" "))
              case Xor.Right(_) => JsObject.empty
            }
          }
        }
      }
    }
  })
} 
开发者ID:ScalaConsultants,项目名称:whisky-tango-foxtrot,代码行数:34,代码来源:UserRoutes.scala

示例8: JSON

//设置package包名称以及导入依赖的类
package falkner.jayson.metrics.io

import java.nio.file.{Files, Path}

import falkner.jayson.metrics._
import spray.json.{JsArray, JsBoolean, JsNumber, JsObject, JsString, JsValue}

import scala.util.{Failure, Success, Try}


object JSON {

  def apply(out: Path, ml: Metrics): Path = apply(out, Seq(ml))

  def apply(out: Path, mls: Seq[Metrics]): Path = Files.write(mkdir(out), JsObject(mls.map(export): _*).prettyPrint.getBytes)

  def export(o: Metrics): (String, JsValue) = (o.namespace, JsObject(export(o.values): _*))

  def export(o: List[Metric]): List[(String, JsValue)] = o.flatMap(_ match {
    case n: Num => noneIfError[JsNumber]((n.name, JsNumber(n.value)))
    case s: Str => noneIfError[JsString]((s.name, JsString(s.value)))
    case b: Bool => noneIfError[JsBoolean]((b.name, JsBoolean(b.value)))
    case n: NumArray => noneIfError[JsArray]((n.name, JsArray(n.values.asInstanceOf[Seq[Int]].map(m => JsNumber(m)).toVector)))
    // flatten out categorical distributions and keep key order
    case cd: CatDist => noneIfError[JsObject](
      (cd.name, JsObject(
        List(("Name", JsString(cd.name)), ("Samples", JsNumber(cd.samples))) ++
          cd.bins.keys.map(k => cd.bins(k) match {
            case s: Short => (k, JsNumber(s))
            case i: Int => (k, JsNumber(i))
            case l: Long => (k, JsNumber(l))
            case f: Float => (k, JsNumber(f))
            case d: Double => (k, JsNumber(d))
          }): _*))
    )
    case d: Metrics => noneIfError[JsObject]((d.name, JsObject(export(d.values): _*)))
  })

  def noneIfError[A](f: => (String, A)): Option[(String, A)] = Try(f) match {
    case Success(s) => Some(s)
    case Failure(t) => None
  }
} 
开发者ID:jfalkner,项目名称:metrics,代码行数:44,代码来源:JSON.scala

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

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

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

示例12: EditsVerification

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

import hmda.model.fi.SubmissionStatus
import spray.json.JsObject

case class EditsVerification(verified: Boolean)
case class EditsVerifiedResponse(verified: Boolean, status: SubmissionStatus)

case class EditInfo(edit: String, description: String)
case class EditCollection(edits: Seq[EditInfo])
case class VerifiableEditCollection(verified: Boolean, edits: Seq[EditInfo])

case class SummaryEditResults(
  syntactical: EditCollection,
  validity: EditCollection,
  quality: VerifiableEditCollection,
  `macro`: VerifiableEditCollection,
  status: SubmissionStatus
)
case class SingleTypeEditResults(edits: Seq[EditInfo], status: SubmissionStatus)

case class EditResult(
  edit: String,
  rows: Seq[EditResultRow],
  path: String,
  currentPage: Int,
  total: Int
) extends PaginatedResponse

case class RowId(rowId: String)
case class EditResultRow(row: RowId, fields: JsObject)

 
开发者ID:cfpb,项目名称:hmda-platform,代码行数:32,代码来源:EditResults.scala

示例13: SubmissionStatusJsonFormat

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

import hmda.model.fi._
import hmda.api.model.institutions.submissions.{ ContactSummary, FileSummary, RespondentSummary, SubmissionSummary }
import hmda.api.model.{ Receipt, Submissions }
import hmda.api.protocol.validation.ValidationResultProtocol
import spray.json.{ DeserializationException, JsNumber, JsObject, JsString, JsValue, RootJsonFormat }

trait SubmissionProtocol extends ValidationResultProtocol {

  implicit object SubmissionStatusJsonFormat extends RootJsonFormat[SubmissionStatus] {
    override def write(status: SubmissionStatus): JsValue = {
      JsObject(
        "code" -> JsNumber(status.code),
        "message" -> JsString(status.message),
        "description" -> JsString(status.description)
      )
    }

    override def read(json: JsValue): SubmissionStatus = {
      json.asJsObject.getFields("code").head match {
        case JsNumber(s) => s.toInt match {
          case 1 => Created
          case 2 => Uploading
          case 3 => Uploaded
          case 4 => Parsing
          case 5 => ParsedWithErrors
          case 6 => Parsed
          case 7 => Validating
          case 8 => ValidatedWithErrors
          case 9 => Validated
          case 10 => Signed
          case -1 =>
            val message = json.asJsObject.getFields("message").head.toString()
            Failed(message.substring(1, message.length - 1))
          case _ => throw DeserializationException("Submission Status expected")
        }
        case _ => throw DeserializationException("Unable to deserialize")

      }
    }
  }

  implicit val submissionIdProtocol = jsonFormat3(SubmissionId.apply)
  implicit val submissionFormat = jsonFormat5(Submission.apply)
  implicit val submissionsFormat = jsonFormat1(Submissions.apply)
  implicit val receiptFormat = jsonFormat3(Receipt.apply)

  implicit val fileSummaryFormat = jsonFormat3(FileSummary.apply)
  implicit val contactSummaryFormat = jsonFormat3(ContactSummary.apply)
  implicit val respondentSummaryFormat = jsonFormat5(RespondentSummary.apply)
  implicit val submissionSummaryFormat = jsonFormat2(SubmissionSummary.apply)
} 
开发者ID:cfpb,项目名称:hmda-platform,代码行数:54,代码来源:SubmissionProtocol.scala

示例14: FilingStatusJsonFormat

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

import hmda.api.model.{ FilingDetail, Filings }
import hmda.model.fi._
import spray.json.{ DefaultJsonProtocol, DeserializationException, JsNumber, JsObject, JsString, JsValue, RootJsonFormat }

trait FilingProtocol extends DefaultJsonProtocol with SubmissionProtocol {
  implicit object FilingStatusJsonFormat extends RootJsonFormat[FilingStatus] {
    override def read(json: JsValue): FilingStatus = {
      json.asJsObject.getFields("message").head match {
        case JsString(s) => s match {
          case "not-started" => NotStarted
          case "in-progress" => InProgress
          case "completed" => Completed
          case "cancelled" => Cancelled
        }
        case _ => throw new DeserializationException("Filing Status expected")
      }
    }

    override def write(status: FilingStatus): JsValue = {
      JsObject(
        "code" -> JsNumber(status.code),
        "message" -> JsString(status.message)
      )
    }
  }

  implicit val filingFormat = jsonFormat6(Filing.apply)
  implicit val filingsFormat = jsonFormat1(Filings.apply)
  implicit val filingDetailFormat = jsonFormat2(FilingDetail.apply)
} 
开发者ID:cfpb,项目名称:hmda-platform,代码行数:33,代码来源:FilingProtocol.scala

示例15: SonicSource

//设置package包名称以及导入依赖的类
package build.unstable.sonicd.source

import java.net.InetSocketAddress

import akka.actor.{ActorContext, Props}
import build.unstable.sonic.JsonProtocol._
import build.unstable.sonic.client.SonicPublisher
import build.unstable.sonic.model.{Query, RequestContext, SonicCommand}
import build.unstable.sonic.scaladsl.Sonic._
import spray.json.JsObject

class SonicSource(q: Query, actorContext: ActorContext, context: RequestContext)
  extends SonicdSource(q, actorContext, context) {

  val host: String = getConfig[String]("host")
  val port: Int = getOption[Int]("port").getOrElse(8889)
  val config: JsObject = getConfig[JsObject]("config")
  val addr = new InetSocketAddress(host, port)

  val query: SonicCommand = Query(q.query, config, q.auth).copy(trace_id = q.traceId)

  val supervisorName = s"sonic_${addr.hashCode()}"

  lazy val publisher: Props = {
    val sonicSupervisor = actorContext.child(supervisorName).getOrElse {
      actorContext.actorOf(sonicSupervisorProps(addr), supervisorName)
    }

    Props(classOf[SonicPublisher], sonicSupervisor, query, false)
  }
} 
开发者ID:ernestrc,项目名称:sonicd,代码行数:32,代码来源:SonicSource.scala


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