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


Scala JsString类代码示例

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


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

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

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

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

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

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

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

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

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

示例12: ModelEntityKeyJsonFormat

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

import core.model.ModelEntityKey
import spray.json.{DeserializationException, JsString, JsValue, RootJsonFormat}

package object json {

  class ModelEntityKeyJsonFormat[T <: ModelEntityKey : Manifest] extends RootJsonFormat[T] {
    def write(obj: T): JsValue = JsString(obj.id.toString)

    def read(json: JsValue): T = json match {
      case JsString(str) =>
        manifest.runtimeClass.getConstructors()(0).newInstance(str).asInstanceOf[T]
      case _ => throw new DeserializationException("ModelEntityKeyJsonFormat:read method: JsString expected")
    }
  }

} 
开发者ID:Lastik,项目名称:money-transfer-sample,代码行数:19,代码来源:package.scala

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

示例14: JsonFormat

//设置package包名称以及导入依赖的类
package org.scalawag.jibe.report

import spray.json.{JsString, JsValue, RootJsonFormat}
import spray.json._
import DefaultJsonProtocol._

object JsonFormat {
  class EnumerationFormat[A](enum: Enumeration) extends RootJsonFormat[A] {
    def write(obj: A): JsValue = JsString(obj.toString)
    def read(json: JsValue): A = json match {
      case JsString(str) => enum.withName(str).asInstanceOf[A]
      case x => throw new RuntimeException(s"unknown enumeration value: $x")
    }
  }

  implicit object mosFormat extends EnumerationFormat[ExecutiveStatus.Value](ExecutiveStatus)
  implicit val mandateStatusFormat = jsonFormat9(MandateStatus.apply)
} 
开发者ID:scalawag,项目名称:jibe,代码行数:19,代码来源:JsonFormat.scala

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


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