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

Scala JsString类代码示例

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

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



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


示例16: StandardJsonProtocol

//设置package包名称以及导入依赖的类
package io.clouderite.commons.scala.berries.json

import java.nio.file.{Path, Paths}
import java.time.Instant

import spray.json.{DeserializationException, JsFalse, JsNumber, JsString, JsTrue, JsValue, RootJsonFormat}

object StandardJsonProtocol {
  implicit val instantJson = InstantJsonFormat
  implicit val pathJson = PathJsonFormat
  implicit val anyJson = PathJsonFormat
}

object InstantJsonFormat extends RootJsonFormat[Instant] {
  def write(obj: Instant): JsValue = JsNumber(obj.toEpochMilli)

  def read(json: JsValue): Instant = json match {
    case JsNumber(number) => Instant.ofEpochMilli(number.toLong)
    case _ => throw DeserializationException("JsNumber expected")
  }
}

object PathJsonFormat extends RootJsonFormat[Path] {
  def write(obj: Path): JsValue = JsString(obj.toString)

  def read(json: JsValue): Path = json match {
    case JsString(str) => Paths.get(str)
    case _ => throw DeserializationException("JsString expected")
  }
}

object AnyJsonFormat extends RootJsonFormat[Any] {
  def write(x: Any): JsValue = x match {
    case n: Int => JsNumber(n)
    case n: Long => JsNumber(n)
    case n: Double => JsNumber(n)
    case n: BigDecimal => JsNumber(n)
    case s: String => JsString(s)
    case b: Boolean if b => JsTrue
    case b: Boolean if !b => JsFalse
  }
  
  def read(value: JsValue): Any = value match {
    case JsNumber(n) => n.doubleValue
    case JsString(s) => s
    case JsTrue => true
    case JsFalse => false
  }
} 
开发者ID:clouderite,项目名称:scala-berries,代码行数:50,代码来源:StandardJsonProtocol.scala


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


示例18: write

//设置package包名称以及导入依赖的类
package csw.apps.clusterseed.admin.internal

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import csw.apps.clusterseed.commons.ClusterSeedLogger
import csw.services.logging.internal.LoggingLevels.Level
import csw.services.logging.models.LogMetadata
import spray.json.{DefaultJsonProtocol, JsString, JsValue, RootJsonFormat}

trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol with ClusterSeedLogger.Simple {
  implicit val levelFormat: RootJsonFormat[Level] = new RootJsonFormat[Level] {
    override def write(obj: Level): JsValue = JsString(obj.name)

    override def read(json: JsValue): Level = json match {
      case JsString(value) ? Level(value)
      case _ ?
        val runtimeException = new RuntimeException(s"can not parse $json")
        log.error(runtimeException.getMessage, ex = runtimeException)
        throw runtimeException
    }
  }

  implicit val logMetadataFormat: RootJsonFormat[LogMetadata] = jsonFormat4(LogMetadata.apply)
} 
开发者ID:tmtsoftware,项目名称:csw-prod,代码行数:24,代码来源:JsonSupport.scala


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


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



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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