本文整理汇总了Scala中org.json4s.JsonAST.JString类的典型用法代码示例。如果您正苦于以下问题:Scala JString类的具体用法?Scala JString怎么用?Scala JString使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了JString类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: Json4sFormattingSerializer
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.utils.json
import org.json4s._
import org.json4s.JsonAST.JString
import org.json4s.MappingException
//TODO: this code should die with scala-dropwizard
class Json4sFormattingSerializer[T](serializer: ObjectSerializer[T])(implicit manifest: Manifest[T]) extends CustomSerializer[T](format => (
{
case JString(str) =>
try {
serializer.deserialize(str)
} catch {
case e: Exception => throw new MappingException(e.getMessage, e)
}
case JNull => null.asInstanceOf[T]
},
{
case value: T =>
try {
JString(serializer.serialize(value))
} catch {
case e: Exception => throw new MappingException(e.getMessage, e)
}
}
))
开发者ID:danewatts,项目名称:zap-automation,代码行数:28,代码来源:Json4sFormattingSerializer.scala
示例2: JsonExtraction
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.utils.json
import java.net.{URI, URL}
import org.json4s.JsonAST.JString
import org.json4s.jackson.JsonMethods.parse
import org.json4s.{CustomSerializer, DefaultFormats, Formats, JNull}
object JsonExtraction {
val formats = DefaultFormats + json4sDateTimeSerializer + json4sLocalDateSerializer + UriSerializer + UrlSerializer + Json4sIntToBigDecimalSerializer
def apply[A](body: String)(implicit m: Manifest[A], formats: Formats = formats): A = extractResponse[A](body)
private def extractResponse[A](body: String)(implicit m: Manifest[A], format: Formats = formats): A = Option(body) match {
case Some(b) if b.length > 0 =>
try {
parse(b, useBigDecimalForDouble = true).extract
} catch {
case t: Throwable =>
throw t
}
case _ => throw new IllegalArgumentException("A string value is required for transformation")
}
case object UriSerializer extends CustomSerializer[URI](format => ( {
case JString(uri) => URI.create(uri)
case JNull => null
}, {
case uri: URI => JString(uri.toString)
}
))
case object UrlSerializer extends CustomSerializer[URL](format => ( {
case JString(url) => new URL(url)
case JNull => null
}, {
case url: URL => JString(url.toString)
}
))
}
开发者ID:danewatts,项目名称:zap-automation,代码行数:43,代码来源:JsonExtraction.scala
示例3: UuidSerializer
//设置package包名称以及导入依赖的类
package org.goingok.data.persistence.db.postgresql
import java.time.OffsetDateTime
import java.util.UUID
import org.json4s.JsonAST.JString
import org.json4s.{CustomSerializer, _}
object UuidSerializer extends CustomSerializer[UUID](format =>
(
{
case JString(s) => UUID.fromString(s)
case JNull => null
},
{
case x: UUID => JString(x.toString)
}
)
)
object OffsetDateTimeSerializer extends CustomSerializer[OffsetDateTime](format => (
{
case JString(s) => OffsetDateTime.parse(s)
case JNull => null
},
{
case o:OffsetDateTime => JString(o.toString)
}
)
)
开发者ID:GoingOK,项目名称:goingok-server,代码行数:32,代码来源:CustomSerialisers.scala
示例4: LocaleCountrySerializer
//设置package包名称以及导入依赖的类
package com.wix.pay.stripe
import java.util.Locale
import org.json4s.JsonAST.JString
import org.json4s.reflect.TypeInfo
import org.json4s.{Formats, JsonDSL, MappingException, Serializer, _}
class LocaleCountrySerializer extends Serializer[Locale] {
private val LocaleClass = classOf[Locale]
def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), Locale] = {
case (TypeInfo(LocaleClass, _), json) => json match {
case JString(country) =>
new Locale("", country)
case x => throw new MappingException("Can't convert " + x + " to LocaleClass")
}
}
def serialize(implicit formats: Formats): PartialFunction[Any, JValue] = {
case x: Locale =>
import JsonDSL._
x.getCountry
}
}
开发者ID:wix,项目名称:libpay-stripe,代码行数:27,代码来源:LocaleCountrySerializer.scala
示例5: Classes
//设置package包名称以及导入依赖的类
package database
import org.json4s.JsonAST.{JField, JInt, JObject, JString}
import org.mongodb.scala.Document
import org.mongodb.scala.model.IndexOptions
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
class Classes extends Database {
private val collection = db.getCollection("classes")
private val resourceFile = "data/classes.json"
def createIndex(): Unit = {
collection.createIndex(Document("char_class" -> 1), IndexOptions().unique(true))
.toFuture
.recoverWith { case e: Throwable => Future.failed(e) }
.onComplete(_ => println("Classes index created"))
}
def importData(): Unit = {
val jsonData = loadJsonResource(resourceFile)
val data: List[Document] = for {
JObject(child) <- jsonData
JField("CharClass", JInt(charClass)) <- child
JField("CharClassName", JString(charClassName)) <- child
JField("Base", JString(base)) <- child
JField("Profession", JString(profession)) <- child
} yield Document(
"char_class" -> charClass.toInt,
"char_class_name" -> charClassName.toString,
"base" -> base.toString,
"profession" -> profession.toString
)
collection.insertMany(data)
.toFuture
.recoverWith { case e: Throwable => Future.failed(e) }
.onComplete(_ => println("Classes data imported"))
}
def getCharClass(charClass: Int): Future[Seq[Document]] = {
val doc = Document(
"char_class" -> charClass
)
collection.find(doc)
.toFuture
.recoverWith { case e: Throwable => Future.failed(e) }
}
}
开发者ID:franblas,项目名称:NAOC,代码行数:53,代码来源:Classes.scala
示例6: SearchableLanguageValueSerializer
//设置package包名称以及导入依赖的类
package no.ndla.articleapi.model.search
import org.json4s.JsonAST.{JArray, JField, JObject, JString}
import org.json4s.{CustomSerializer, MappingException}
import no.ndla.articleapi.model.domain.Language.UnknownLanguage
class SearchableLanguageValueSerializer extends CustomSerializer[SearchableLanguageValues](format => ( {
case JObject(items) => SearchableLanguageValues(items.map {
case JField(name, JString(value)) => LanguageValue(Some(name), value)
})
}, {
case x: SearchableLanguageValues =>
JObject(x.languageValues.map(languageValue => JField(languageValue.lang.getOrElse(UnknownLanguage), JString(languageValue.value))).toList)
}))
class SearchableLanguageListSerializer extends CustomSerializer[SearchableLanguageList](format => ( {
case JObject(items) => {
SearchableLanguageList(items.map{
case JField(name, JArray(fieldItems)) => LanguageValue(Some(name), fieldItems.map{
case JString(value) => value
case x => throw new MappingException(s"Cannot convert $x to SearchableLanguageList")
}.to[Seq])
})
}
}, {
case x: SearchableLanguageList =>
JObject(x.languageValues.map(languageValue => JField(languageValue.lang.getOrElse(UnknownLanguage), JArray(languageValue.value.map(lv => JString(lv)).toList))).toList)
}))
object SearchableLanguageFormats {
val JSonFormats = org.json4s.DefaultFormats + new SearchableLanguageValueSerializer + new SearchableLanguageListSerializer
}
开发者ID:NDLANO,项目名称:article-api,代码行数:34,代码来源:SearchableLanguageFormats.scala
示例7: OptionCellSerializer
//设置package包名称以及导入依赖的类
package com.ntsdev.connect4.wire
import com.ntsdev.connect4.model.Cell
import org.json4s.CustomSerializer
import org.json4s.JsonAST.{JField, JObject, JString}
class OptionCellSerializer extends CustomSerializer[Option[Cell]](format => (
{
case JObject(JField("cell", JString(s)) :: Nil) =>
Cell.fromString(s)
},
{
case x: Option[_] =>
if(x.isDefined) {
val value = x.get.toString
JObject(JField("cell", JString(value)))
} else {
JObject(JField("cell", JString("[-]")))
}
}
))
开发者ID:neilshannon,项目名称:connect4,代码行数:25,代码来源:OptionCellSerializer.scala
示例8: PedestrianIncident
//设置package包名称以及导入依赖的类
package searching
import mapdomain.graph.Coordinate
import org.json4s.CustomSerializer
import org.json4s.JsonAST.JString
case class PedestrianIncident(`type`: IncidentType,
position: Option[Coordinate] = None,
from: Option[Coordinate] = None,
to: Option[Coordinate] = None)
sealed trait IncidentType
case object SidewalkIncidentType extends IncidentType
case object RampIncidentType extends IncidentType
case object StopIncidentType extends IncidentType
object IncidentType {
val keyMap: Map[String, IncidentType] = Map(
"sidewalk" -> SidewalkIncidentType,
"ramp" -> RampIncidentType) withDefaultValue SidewalkIncidentType
}
case object IncidentTypeSerializer extends CustomSerializer[IncidentType](format ? ({
case JString(s) ? IncidentType.keyMap(s)
}, {
case incidentType: IncidentType ? JString(IncidentType.keyMap.find(i ? incidentType.equals(i._2)).get._1)
}))
开发者ID:cspinetta,项目名称:footpath-routing,代码行数:28,代码来源:Incidents.scala
示例9: Device
//设置package包名称以及导入依赖的类
package com.ubirch.avatar.model.db.device
import java.util.UUID
import com.ubirch.avatar.config.Config
import org.joda.time.{DateTime, DateTimeZone}
import org.json4s.JValue
import org.json4s.JsonAST.{JBool, JString}
case class Device(deviceId: String,
groups: Set[UUID] = Set.empty,
deviceTypeKey: String = "unknownDeviceType",
deviceName: String = "unnamedDevice",
hwDeviceId: String = "unknownHwDeviceId",
hashedHwDeviceId: String = "unknownHwDeviceId",
tags: Set[String] = Set(),
deviceConfig: Option[JValue] = None,
deviceProperties: Option[JValue] = None,
subQueues: Option[Set[String]] = None,
pubQueues: Option[Set[String]] = Some(Set(Config.awsSqsQueueTransformerOut)),
avatarLastUpdated: Option[DateTime] = None,
deviceLastUpdated: Option[DateTime] = None,
updated: Option[DateTime] = None,
created: DateTime = DateTime.now(DateTimeZone.UTC)
) {
override def equals(obj: scala.Any): Boolean = {
obj match {
case dev: Device =>
if (
dev.deviceId == this.deviceId
)
true
else
false
case _ => false
}
}
override def hashCode(): Int = this.deviceId.hashCode
def checkProperty(propertyKey: String): Boolean = {
if (deviceConfig.isDefined) {
(deviceProperties.get.camelizeKeys \ propertyKey).equals(JString("true")) ||
(deviceProperties.get.camelizeKeys \ propertyKey).equals(JBool(true))
}
else
false
}
}
开发者ID:ubirch,项目名称:ubirch-avatar-service,代码行数:52,代码来源:Device.scala
示例10: MongoQueryParser
//设置package包名称以及导入依赖的类
package service
import org.json4s.JsonAST.JBool
import org.json4s.JsonAST.JDecimal
import org.json4s.JsonAST.JDouble
import org.json4s.JsonAST.JInt
import org.json4s.JsonAST.JObject
import org.json4s.JsonAST.JString
import org.json4s.native.JsonMethods
import org.mongodb.scala.bson.collection.immutable.Document
class MongoQueryParser {
def parse(query: String): Document = {
val json = JsonMethods.parse(query, useBigDecimalForDouble = true)
val mongoQuery: List[Document] =
for {
JObject(child) <- json
(fieldName, value) <- child
} yield {
value match {
case JString(s) => Document(fieldName -> s)
case JDouble(num) => Document(fieldName -> num)
case JDecimal(num) => Document(fieldName -> num)
case JInt(num) => Document(fieldName -> num.intValue())
case JBool(bool) => Document(fieldName -> bool)
case _ => throw new IllegalArgumentException(f"Error when processing field '$fieldName%s': Unsupported type: '$value'")
}
}
mongoQuery.reduce(_ ++ _)
}
}
开发者ID:dougsleite,项目名称:oak,代码行数:34,代码来源:MongoQueryParser.scala
示例11: NoneJNullSerializer
//设置package包名称以及导入依赖的类
package io.vamp.pulse.util
import java.time.format.DateTimeFormatter.ISO_OFFSET_DATE_TIME
import java.time.{Instant, OffsetDateTime, ZoneId}
import io.vamp.pulse.api.AggregatorType
import org.json4s.JsonAST.{JNull, JString}
import org.json4s._
import org.json4s.ext.EnumNameSerializer
class NoneJNullSerializer extends CustomSerializer[Option[_]](format => ({ case JNull => None }, { case None => JNull }))
class OffsetDateTimeSerializer extends CustomSerializer[OffsetDateTime](
format => (
{
case JString(str) => OffsetDateTime.parse(str)
case JDouble(num) =>
OffsetDateTime.from(Instant.ofEpochSecond(num.toLong).atZone(ZoneId.of("UTC")))
},
{ case date: OffsetDateTime => JString(date.format(ISO_OFFSET_DATE_TIME))}
)
)
object Serializers {
implicit val formats = DefaultFormats + new OffsetDateTimeSerializer() + new EnumNameSerializer(AggregatorType)
}
开发者ID:carriercomm,项目名称:vamp-pulse-api,代码行数:28,代码来源:Serializers.scala
示例12: SighashSpec
//设置package包名称以及导入依赖的类
package fr.acinq.syscoin.reference
import java.io.InputStreamReader
import fr.acinq.syscoin._
import org.json4s.DefaultFormats
import org.json4s.JsonAST.{JInt, JString, JValue}
import org.json4s.jackson.JsonMethods
import org.junit.runner.RunWith
import org.scalatest.FlatSpec
import org.scalatest.junit.JUnitRunner
@RunWith(classOf[JUnitRunner])
class SighashSpec extends FlatSpec {
implicit val format = DefaultFormats
"syscoin-lib" should "pass reference client sighash tests" in {
val stream = classOf[Base58Spec].getResourceAsStream("/data/sighash.json")
val json = JsonMethods.parse(new InputStreamReader(stream))
// use tail to skip the first line of the .json file
json.extract[List[List[JValue]]].tail.map(_ match {
case JString(raw_transaction) :: JString(script) :: JInt(input_index) :: JInt(hashType) :: JString(signature_hash) :: Nil => {
val tx = Transaction.read(raw_transaction)
val hash = Transaction.hashForSigning(tx, input_index.intValue, fromHexString(script), hashType.intValue)
assert(toHexString(hash.reverse) === signature_hash)
}
case _ => println("warning: could not parse sighash.json properly!")
})
}
}
开发者ID:sidhujag,项目名称:syscoin-lib,代码行数:31,代码来源:SighashSpec.scala
示例13:
//设置package包名称以及导入依赖的类
package smarthouse.restapi.http.ws
import java.net.URI
import java.time.OffsetDateTime
import akka.cluster.MemberStatus
import org.json4s.CustomSerializer
import org.json4s.JsonAST.JString
trait JsonSerializers {
val memberStatusSerializer = new CustomSerializer[MemberStatus](format => ( {
case JString("Exiting") => MemberStatus.Exiting
case JString("Up") => MemberStatus.Up
case JString("Joining") => MemberStatus.Joining
case JString("Leaving") => MemberStatus.Leaving
case JString("Removed") => MemberStatus.Removed
case JString("Down") => MemberStatus.Down
}, {
case x: MemberStatus =>
JString(x.toString)
}
))
val uriSerializer = new CustomSerializer[URI](format => ( {
case JString(string) => new URI(string)
}, {
case x: URI =>
JString(x.toString)
}
))
val offsetDateTime = new CustomSerializer[OffsetDateTime](format => ( {
case JString(string) => OffsetDateTime.parse(string)
}, {
case x: OffsetDateTime =>
JString(x.toLocalDateTime.toString)
}
))
}
开发者ID:andrewobukhov,项目名称:smart-house,代码行数:40,代码来源:JsonSerializers.scala
示例14: ApiDecoder
//设置package包名称以及导入依赖的类
package smarthouse.restapi.http.ws
import org.json4s.JsonAST.JString
import org.json4s.NoTypeHints
import org.json4s.jackson.JsonMethods._
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization._
import smarthouse.restapi.http.ws.models.{ApiMessage, Heartbeat}
import scala.util.{Failure, Success, Try}
object ApiDecoder extends JsonSerializers {
implicit val formats = Serialization.formats(NoTypeHints) + memberStatusSerializer + uriSerializer + offsetDateTime
def decodeRequest(requestString: String): Option[ApiMessage] = {
Try {
parse(requestString) \ "messageType" match {
case JString("Heartbeat") => read[Heartbeat](requestString)
case _ => throw InvalidRequestException
}
} match {
case Success(x) => Some(x)
case Failure(_) => None
}
}
def encodeRequest(apiMessage: ApiMessage): String = {
write(apiMessage)
}
def encodeCustom(msg: AnyRef): String = {
write(msg)
}
case object InvalidRequestException extends RuntimeException
}
开发者ID:andrewobukhov,项目名称:smart-house,代码行数:39,代码来源:ApiDecoder.scala
示例15: AddNew
//设置package包名称以及导入依赖的类
package codes.bytes.quaich.samples.plain
import java.io.OutputStream
import akka.typed.scaladsl.Actor
import akka.typed.scaladsl.AskPattern._
import akka.typed.{ActorRef, ActorSystem, Behavior}
import akka.util.Timeout
import codes.bytes.quaich.api.LambdaContext
import codes.bytes.quaich.api.direct.{DirectLambda, DirectLambdaHandler}
import org.json4s.JValue
import org.json4s.JsonAST.JString
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._
sealed trait NameMsg
final case class AddNew(lang: String, replyTo: ActorRef[Array[String]]) extends NameMsg
@DirectLambda
class PlainLambda extends DirectLambdaHandler {
implicit val timeout = Timeout(1.second)
val namedBehavior: Behavior[NameMsg] = Actor.mutable[NameMsg](ctx => new NameActor)
val system: ActorSystem[NameMsg] = ActorSystem("hello", namedBehavior)
override protected def handleEvent(json: JValue, output: OutputStream)(implicit ctx: LambdaContext) {
json match {
case JString(lang) =>
implicit val scheduler = system.scheduler
val results: Future[Array[String]] = system ? { ref => AddNew(lang, ref) }
writeJson (output, Await.result (results, timeout.duration) )
case other =>
ctx.log.error(s"Uncreckognized JSON format")
}
}
}
class NameActor extends Actor.MutableBehavior[NameMsg] {
private var names: List[String] = Nil
override def onMessage(msg: NameMsg): Behavior[NameMsg] = {
msg match {
case AddNew(lang, replyTo) =>
names = lang :: names
replyTo ! names.toArray
}
this
}
}
开发者ID:pdolega,项目名称:quaich-other-samples,代码行数:56,代码来源:AkkaLambda.scala
示例16: Hit
//设置package包名称以及导入依赖的类
package model
import org.json4s.CustomSerializer
import org.json4s.JsonAST.{JNull, JString}
trait ResultShooting
case object Hit extends ResultShooting
case object Missed extends ResultShooting
case object AlreadyTaken extends ResultShooting
case object Sunk extends ResultShooting
case object AllSunken extends ResultShooting
object ResultShootingSerializer extends CustomSerializer[ResultShooting](format => (
{
case JString(resultShooting) => resultShooting match {
case "Hit" => Hit
case "Missed" => Missed
case "AlreadyTaken" => AlreadyTaken
case "Sunk" => Sunk
case _ => Missed
}
case JNull => null
},
{
case resultShooting:ResultShooting => JString(resultShooting.getClass.getSimpleName.replace("$",""))
}))
开发者ID:apellizzaro,项目名称:Battlefield,代码行数:29,代码来源:ResultShooting.scala
示例17: EmptySea
//设置package包名称以及导入依赖的类
package model
import org.json4s.CustomSerializer
import org.json4s.JsonAST.{JNull, JString}
sealed trait SeaStatus
case object EmptySea extends SeaStatus
case object MissedShot extends SeaStatus
case object BattleShipSafe extends SeaStatus
case object BattleShipHit extends SeaStatus
case object BattleShipSunk extends SeaStatus
case object SeaStatusSerializer extends CustomSerializer[SeaStatus](format => (
{
case JString(seastatus) => seastatus match {
case "EmptySea" => EmptySea
case "MissedShot" => MissedShot
case "BattleShipSafe" => BattleShipSafe
case "BattleShipHit" => BattleShipHit
case "BattleShipSunk" => BattleShipSunk
case _ => EmptySea
}
case JNull => null
},
{
case seaStatus:SeaStatus => JString(seaStatus.getClass.getSimpleName.replace("$",""))
}))
开发者ID:apellizzaro,项目名称:Battlefield,代码行数:30,代码来源:SeaStatus.scala
示例18: GameSettingUp
//设置package包名称以及导入依赖的类
package model
import org.json4s.CustomSerializer
import org.json4s.JsonAST.{JNull, JString}
sealed trait GameStatus
case object GameSettingUp extends GameStatus
case object GameInProgress extends GameStatus
case object GameEnded extends GameStatus
object GameStatusSerializer extends CustomSerializer[GameStatus](format => (
{
case JString(gameStatus) => gameStatus match {
case "GameSettingUp" => GameSettingUp
case "GameInProgress" => GameInProgress
case "GameEnded" => GameEnded
}
case JNull => null
},
{
case gameStatus:GameStatus => JString(gameStatus.getClass.getSimpleName.replace("$",""))
}))
开发者ID:apellizzaro,项目名称:Battlefield,代码行数:26,代码来源:GameStatus.scala
示例19: Dropped
//设置package包名称以及导入依赖的类
package com.pagerduty.scheduler.model
import org.json4s.CustomSerializer
import org.json4s.JsonAST.JString
case object Dropped extends CompletionResult {
override protected def stringValue = "Dropped"
override def isComplete: Boolean = true
}
def fromString(completionResult: String): Option[CompletionResult] = {
completionResult.toLowerCase match {
case "incomplete" => Some(Incomplete)
case "success" => Some(Success)
case "failure" => Some(Failure)
case "dropped" => Some(Dropped)
case _ => None
}
}
}
class CompletionResultSerializer
extends CustomSerializer[CompletionResult](
format =>
({
case JString(s) => CompletionResult.fromString(s).getOrElse(CompletionResult.Failure)
}, {
case cr: CompletionResult => JString(cr.toString)
})
)
开发者ID:PagerDuty,项目名称:scheduler,代码行数:32,代码来源:CompletionResult.scala
示例20: JsonSerializers
//设置package包名称以及导入依赖的类
package io.iohk.ethereum.jsonrpc
import akka.util.ByteString
import io.iohk.ethereum.domain.Address
import org.json4s.JsonAST.{JNull, JString}
import org.json4s.CustomSerializer
import org.spongycastle.util.encoders.Hex
object JsonSerializers {
object UnformattedDataJsonSerializer extends CustomSerializer[ByteString](_ =>
(
{ PartialFunction.empty },
{ case bs: ByteString => JString(s"0x${Hex.toHexString(bs.toArray)}") }
)
)
object QuantitiesSerializer extends CustomSerializer[BigInt](_ =>
(
{PartialFunction.empty},
{
case n: BigInt =>
if(n == 0)
JString("0x0")
else
JString(s"0x${Hex.toHexString(n.toByteArray).dropWhile(_ == '0')}")
}
)
)
object OptionNoneToJNullSerializer extends CustomSerializer[Option[_]](formats =>
(
{PartialFunction.empty},
{ case None => JNull }
)
)
object AddressJsonSerializer extends CustomSerializer[Address](_ =>
(
{ PartialFunction.empty },
{ case addr: Address => JString(s"0x${Hex.toHexString(addr.bytes.toArray)}") }
)
)
}
开发者ID:input-output-hk,项目名称:etc-client,代码行数:46,代码来源:JsonSerializers.scala
注:本文中的org.json4s.JsonAST.JString类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论