本文整理汇总了Scala中org.json4s.JsonAST.JString类的典型用法代码示例。如果您正苦于以下问题:Scala JString类的具体用法?Scala JString怎么用?Scala JString使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了JString类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
}
}
))
示例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)
}
))
}
示例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)
}
)
)
示例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
}
}
示例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) }
}
}
示例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
}
示例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("[-]")))
}
}
))
示例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)
}))
示例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
}
}
示例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(_ ++ _)
}
}
示例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)
}
示例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!")
})
}
}
示例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)
}
))
}
示例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
}
示例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
}
}