本文整理汇总了Scala中io.circe.Json类的典型用法代码示例。如果您正苦于以下问题:Scala Json类的具体用法?Scala Json怎么用?Scala Json使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Json类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: route
//设置package包名称以及导入依赖的类
package com.ulasakdeniz.hakker
import akka.http.scaladsl.marshalling.{Marshal, ToEntityMarshaller}
import akka.http.scaladsl.model.{HttpHeader, HttpResponse, ResponseEntity, StatusCode}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import com.typesafe.config.ConfigFactory
import com.ulasakdeniz.hakker.template.Render
import de.heikoseeberger.akkahttpcirce.CirceSupport._
import io.circe.{Encoder, Json}
import io.circe.syntax._
import scala.collection.immutable
import scala.concurrent.ExecutionContext
trait Controller extends Render {
override lazy val config = ConfigFactory.load()
val StatusCodes = akka.http.scaladsl.model.StatusCodes
def route: Route
def apply(): Route = {
get {
// render frontend files
pathPrefix("js") {
renderDir("js")
}
} ~ route
}
def send(statusCode: StatusCode): Route = complete(statusCode)
def send[T](statusCode: StatusCode, content: T, headers: immutable.Seq[HttpHeader] = Nil)(
implicit marshaller: ToEntityMarshaller[T],
ec: ExecutionContext): Route = {
val response = Marshal(content)
.to[ResponseEntity](marshaller, ec)
.map(entity => {
HttpResponse(statusCode, headers = headers).withEntity(entity)
})
complete(response)
}
def sendJson[T](statusCode: StatusCode, content: T)(implicit encoder: Encoder[T],
ec: ExecutionContext): Route = {
sendJson(statusCode, content.asJson)
}
def sendJson[T](content: T)(implicit encoder: Encoder[T], ec: ExecutionContext): Route = {
sendJson(StatusCodes.OK, content)
}
def sendJson(statusCode: StatusCode, json: Json)(implicit ec: ExecutionContext): Route = {
send(statusCode, Option(json.noSpaces))
}
}
示例2: PayloadParser
//设置package包名称以及导入依赖的类
package akkord.parser
import akka.actor.{Actor, ActorRef, Props}
import akka.http.scaladsl.model.ws.TextMessage
import akkord.DiscordBot._
import io.circe.parser.parse
import io.circe.{HCursor, Json}
class PayloadParser(bot: ActorRef) extends Actor {
import PayloadParser._
val eventParser = context.actorOf(Props(classOf[EventParser]))
override def receive = {
case TextMessage.Strict(text) => parseText(text)
case Payload(0, cursor) => parseEvent(cursor)
case Payload(3, _) => sender ! StatusUpdate
case Payload(7, _) => sender ! Reconnect
case Payload(9, _) => sender ! InvalidSession
case Payload(10, cursor) => parseHello(cursor)
case Payload(11, _) => sender ! HeartBeatAck
case Payload(-1, cursor) => sender ! UnsupportedMessage(cursor.value.toString())
}
private def parseText(text: String): Unit = {
val json = parse(text).getOrElse(Json.Null)
val cursor = json.hcursor
val op = cursor.get[Int]("op").toOption
self forward Payload(op getOrElse -1, cursor)
}
private def parseEvent(cursor: HCursor): Unit = {
cursor
.get[Int]("s")
.toOption
.foreach(s => bot ! NewSeq(s))
cursor
.get[String]("t")
.toOption
.foreach(t => eventParser forward EventParser.Event(t, cursor))
}
private def parseHello(cursor: HCursor): Unit = {
cursor
.downField("d")
.get[Int]("heartbeat_interval")
.toOption
.foreach(interval => sender ! Hello(interval))
}
}
object PayloadParser {
case class Payload(op: Int, cursor: HCursor)
}
示例3: circeableFrameFormat
//设置package包名称以及导入依赖的类
package org.http4s.akka
import io.circe.{Decoder, Encoder, Json}
import io.circe.parser._
import org.http4s.{Charset, DefaultCharset, UrlForm}
import org.http4s.websocket.WebsocketBits._
import play.twirl.api._
implicit def circeableFrameFormat[A: Encoder : Decoder]: FrameFormatter[A] = jsonFrameFormatter.transform[A](
Encoder[A].apply(_),
Decoder[A].decodeJson(_).toTry.get
)
//=== TWIRL ===
implicit val htmlFrameFormatter: FrameFormatter[Html] = stringFrameFormatter.transform(_.body, Html.apply)
implicit val xmlFrameFormatter: FrameFormatter[Xml] = stringFrameFormatter.transform(_.body, Xml.apply)
implicit val txtFrameFormatter: FrameFormatter[Txt] = stringFrameFormatter.transform(_.body, Txt.apply)
implicit val javaScriptFrameFormatter: FrameFormatter[JavaScript] = stringFrameFormatter.transform(_.body, JavaScript.apply)
}
示例4: apply
//设置package包名称以及导入依赖的类
package swaggerblocks.rendering.yaml
import io.circe.yaml.parser.parse
import io.circe.{Encoder, Json}
import swaggerblocks.internal.specModels._
import cats.syntax.either._
trait SpecEncoders {
implicit val encodeSpecExample = new Encoder[SpecExample] {
def apply(se: SpecExample): Json = {
// Since we control the serialization this should be always valid
parse(se.value).valueOr(throw _)
}
}
implicit val encodeSpecValue = new Encoder[SpecValue] {
def apply(sv: SpecValue): Json = sv match {
case SpecValue.StringValue(v) => Json.fromString(v)
case SpecValue.IntValue(v) => Json.fromInt(v)
case SpecValue.BooleanValue(v) => Json.fromBoolean(v)
case SpecValue.ListValue(list) => Json.fromValues(list.map(apply))
case SpecValue.MapValue(mapping) => Json.fromFields(mapping.mapValues(apply))
}
}
}
示例5: ArangoCursor
//设置package包名称以及导入依赖的类
package com.outr.arango
import com.outr.arango.rest.{QueryRequest, QueryRequestOptions, QueryResponse}
import io.circe.{Decoder, Json}
import io.circe.generic.auto._
import io.youi.http.Method
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
class ArangoCursor(arangoDB: ArangoDB) {
def apply[T](query: Query,
count: Boolean = false,
batchSize: Option[Int] = None,
cache: Option[Boolean] = None,
memoryLimit: Option[Long] = None,
ttl: Option[Int] = None,
options: QueryRequestOptions = QueryRequestOptions())
(implicit decoder: Decoder[T]): Future[QueryResponse[T]] = {
val bindVars = Json.obj(query.args.map {
case (key, value) => {
val argValue: Json = value match {
case Value.Null => Json.Null
case StringValue(s) => Json.fromString(s)
case IntValue(i) => Json.fromInt(i)
case LongValue(l) => Json.fromLong(l)
case DoubleValue(d) => Json.fromDoubleOrNull(d)
}
key -> argValue
}
}.toSeq: _*)
val request = QueryRequest(
query = query.value,
bindVars = bindVars,
count = count,
batchSize = batchSize,
cache = cache,
memoryLimit = memoryLimit,
ttl = ttl,
options = options
)
arangoDB.restful[QueryRequest, QueryResponse[T]]("cursor", request)
}
def paged[T](query: Query,
batchSize: Int = 100,
cache: Option[Boolean] = None,
memoryLimit: Option[Long] = None,
ttl: Option[Int] = None,
options: QueryRequestOptions = QueryRequestOptions())
(implicit decoder: Decoder[T]): Future[QueryResponsePagination[T]] = {
val count = true
apply[T](query, count, Some(batchSize), cache, memoryLimit, ttl, options).map(r => QueryResponsePagination[T](this, r))
}
def get[T](id: String)
(implicit decoder: Decoder[T]): Future[QueryResponse[T]] = {
arangoDB.call[QueryResponse[T]](s"cursor/$id", Method.Put)
}
}
示例6: QueryRequest
//设置package包名称以及导入依赖的类
package com.outr.arango.rest
import io.circe.Json
case class QueryRequest(query: String,
bindVars: Json,
count: Boolean,
batchSize: Option[Int],
cache: Option[Boolean],
memoryLimit: Option[Long],
ttl: Option[Int],
options: QueryRequestOptions)
case class QueryRequestOptions(profile: Option[Boolean] = None,
`optimizer.rules`: Option[String] = None,
sateliteSyncWait: Double = 60.0,
fullCount: Option[Boolean] = None,
maxPlans: Option[Int] = None)
示例7: ADProof
//设置package包名称以及导入依赖的类
package org.ergoplatform.modifiers.history
import com.google.common.primitives.Bytes
import io.circe.Json
import io.circe.syntax._
import org.ergoplatform.modifiers.history.ADProof.ProofRepresentation
import org.ergoplatform.modifiers.mempool.proposition.{AnyoneCanSpendNoncedBox, AnyoneCanSpendProposition}
import org.ergoplatform.modifiers.{ErgoPersistentModifier, ModifierWithDigest}
import org.ergoplatform.nodeView.state.ErgoState.Digest
import org.ergoplatform.settings.{Algos, Constants}
import scorex.core.NodeViewModifier.{ModifierId, ModifierTypeId}
import scorex.core.serialization.Serializer
import scorex.core.transaction.state.{BoxStateChangeOperation, BoxStateChanges, Insertion, Removal}
import scorex.crypto.authds.avltree.AVLValue
import scorex.crypto.authds.avltree.batch.{BatchAVLVerifier, Insert, Modification, Remove}
import scorex.crypto.encode.Base58
import scorex.crypto.hash.Blake2b256Unsafe
import scala.util.{Failure, Success, Try}
case class ADProof(headerId: ModifierId, proofBytes: ProofRepresentation) extends ErgoPersistentModifier
with ModifierWithDigest {
override def digest: Array[ModifierTypeId] = ADProof.proofDigest(proofBytes)
override val modifierTypeId: ModifierTypeId = ADProof.ModifierTypeId
override type M = ADProof
override lazy val serializer: Serializer[ADProof] = ADProofSerializer
override lazy val json: Json = Map(
"headerId" -> Base58.encode(headerId).asJson,
"proofBytes" -> Base58.encode(proofBytes).asJson,
"digest" -> Base58.encode(digest).asJson,
).asJson
override def toString: String = s"ADProofs(${Base58.encode(id)},${Base58.encode(headerId)},${Base58.encode(proofBytes)})"
def changeToMod(change: BoxStateChangeOperation[AnyoneCanSpendProposition, AnyoneCanSpendNoncedBox]): Modification =
change match {
case i: Insertion[AnyoneCanSpendProposition, AnyoneCanSpendNoncedBox] =>
Insert(i.box.id, i.box.bytes)
case r: Removal[AnyoneCanSpendProposition, AnyoneCanSpendNoncedBox] =>
Remove(r.boxId)
}
}
object ADProofSerializer extends Serializer[ADProof] {
override def toBytes(obj: ADProof): Array[Byte] = Bytes.concat(obj.headerId, obj.proofBytes)
override def parseBytes(bytes: Array[Byte]): Try[ADProof] = Try {
ADProof(bytes.take(Constants.ModifierIdSize), bytes.slice(Constants.ModifierIdSize, bytes.length))
}
}
示例8: BlockTransactions
//设置package包名称以及导入依赖的类
package org.ergoplatform.modifiers.history
import com.google.common.primitives.{Bytes, Shorts}
import io.circe.Json
import org.ergoplatform.modifiers.mempool.{AnyoneCanSpendTransaction, AnyoneCanSpendTransactionSerializer}
import org.ergoplatform.modifiers.{ErgoPersistentModifier, ModifierWithDigest}
import org.ergoplatform.settings.{Algos, Constants}
import scorex.core.NodeViewModifier.{ModifierId, ModifierTypeId}
import scorex.core.serialization.Serializer
import scorex.core.utils.concatBytes
import scorex.crypto.encode.Base58
import scala.util.Try
case class BlockTransactions(headerId: ModifierId, txs: Seq[AnyoneCanSpendTransaction]) extends ErgoPersistentModifier
with ModifierWithDigest {
assert(txs.nonEmpty, "Block should contain at least 1 coinbase-like transaction")
override val modifierTypeId: ModifierTypeId = BlockTransactions.ModifierTypeId
override def digest: Array[ModifierTypeId] = BlockTransactions.rootHash(txs.map(_.id))
override type M = BlockTransactions
override lazy val serializer: Serializer[BlockTransactions] = BlockTransactionsSerializer
override lazy val json: Json = ???
override def toString: String = s"BlockTransactions(${Base58.encode(id)},${Base58.encode(headerId)},$txs)"
}
object BlockTransactions {
val ModifierTypeId: Byte = 102: Byte
def rootHash(ids: Seq[Array[Byte]]): Array[Byte] = Algos.merkleTreeRoot(ids)
}
object BlockTransactionsSerializer extends Serializer[BlockTransactions] {
override def toBytes(obj: BlockTransactions): Array[ModifierTypeId] = {
val txsBytes = concatBytes(obj.txs.map(tx => Bytes.concat(Shorts.toByteArray(tx.bytes.length.toShort), tx.bytes)))
Bytes.concat(obj.headerId, txsBytes)
}
override def parseBytes(bytes: Array[ModifierTypeId]): Try[BlockTransactions] = Try {
val headerId = bytes.slice(0, Constants.ModifierIdSize)
def parseTransactions(index: Int, acc: Seq[AnyoneCanSpendTransaction]): BlockTransactions = {
if (index == bytes.length) {
BlockTransactions(headerId, acc)
} else {
val txLength = Shorts.fromByteArray(bytes.slice(index, index + 2))
val tx = AnyoneCanSpendTransactionSerializer.parseBytes(bytes.slice(index + 2, index + 2 + txLength)).get
parseTransactions(index + 2 + txLength, acc :+ tx)
}
}
parseTransactions(Constants.ModifierIdSize, Seq())
}
}
示例9: AnyoneCanSpendNoncedBox
//设置package包名称以及导入依赖的类
package org.ergoplatform.modifiers.mempool.proposition
import com.google.common.primitives.Longs
import io.circe.Json
import io.circe.syntax._
import org.ergoplatform.settings.Algos
import scorex.core.serialization.{JsonSerializable, Serializer}
import scorex.core.transaction.box.Box
import scorex.crypto.encode.Base58
import scala.util.Try
case class AnyoneCanSpendNoncedBox(override val proposition: AnyoneCanSpendProposition,
nonce: Long,
override val value: Long
) extends Box[AnyoneCanSpendProposition] with JsonSerializable {
override lazy val json: Json = Map(
"id" -> Base58.encode(id).asJson,
"nonce" -> nonce.asJson,
"value" -> value.asJson
).asJson
override val id: Array[Byte] = Algos.hash(Longs.toByteArray(nonce))
override type M = AnyoneCanSpendNoncedBox
override lazy val serializer: Serializer[AnyoneCanSpendNoncedBox] = AnyoneCanSpendNoncedBoxSerializer
}
object AnyoneCanSpendNoncedBox {
def idFromBox(prop: AnyoneCanSpendProposition, nonce: Long): Array[Byte] =
Algos.hash(prop.serializer.toBytes(prop) ++ Longs.toByteArray(nonce))
}
object AnyoneCanSpendNoncedBoxSerializer extends Serializer[AnyoneCanSpendNoncedBox] {
val Length: Int = AnyoneCanSpendPropositionSerializer.Length + 8 + 8
override def toBytes(obj: AnyoneCanSpendNoncedBox): Array[Byte] =
obj.proposition.serializer.toBytes(obj.proposition) ++
Longs.toByteArray(obj.nonce) ++
Longs.toByteArray(obj.value)
override def parseBytes(bytes: Array[Byte]): Try[AnyoneCanSpendNoncedBox] = Try {
val proposition = AnyoneCanSpendPropositionSerializer.parseBytes(bytes.take(1)).get
val nonce = Longs.fromByteArray(bytes.slice(1, 9))
val value = Longs.fromByteArray(bytes.slice(9, 17))
AnyoneCanSpendNoncedBox(proposition, nonce, value)
}
}
示例10: CirceSpec
//设置package包名称以及导入依赖的类
package org.mdoc.common.model
import cats.data.Xor
import io.circe.{ Decoder, Encoder, Json }
import org.mdoc.common.model.circe._
import org.scalacheck.Prop._
import org.scalacheck.Properties
import scodec.bits.ByteVector
object CirceSpec extends Properties("circe") {
property("Decoder[ByteVector] success") = secure {
Decoder[ByteVector].decodeJson(Json.string("SGVsbG8=")) ?=
Xor.right(ByteVector("Hello".getBytes))
}
property("Decoder[ByteVector] failure") = secure {
Decoder[ByteVector].decodeJson(Json.string("???")).isLeft
}
property("Encoder[ByteVector]") = secure {
Encoder[ByteVector].apply(ByteVector("Hello".getBytes)) ?=
Json.string("SGVsbG8=")
}
}
示例11: Config
//设置package包名称以及导入依赖的类
package wiro
import io.circe.Json
case class Config(
host: String,
port: Int
)
case class WiroRequest(
args: String
)
case class RpcRequest(
path: Seq[String],
args: Map[String, Json]
)
case class Auth(
token: String
)
示例12: SlickCompareOperation
//设置package包名称以及导入依赖的类
package net.scalax.fsn.json.operation
import io.circe.Json
import net.scalax.fsn.common.atomic.FProperty
import net.scalax.fsn.core._
import net.scalax.fsn.json.atomic.{ CompareToStringConvert, SlickCompare }
import net.scalax.fsn.slick.helpers.{ FilterModel, FilterModelHelper }
import shapeless._
object SlickCompareOperation extends FilterModelHelper {
val unfullReadCompareGen = FPile.transformTreeList {
new FAtomicQuery(_) {
val aa = withRep(needAtomic[SlickCompare] :: needAtomic[FProperty] :: needAtomic[CompareToStringConvert] :: FANil)
.mapTo {
case (jsonReader :: property :: compareCv :: HNil, _) =>
val tran: Map[String, Json] => FAtomicValueImpl[path.DataType] = { sourceData: Map[String, Json] =>
sourceData.get(property.proName) match {
case Some(json) =>
json.as[FilterModel[jsonReader.DataType]](jsonReader.reader) match {
case Right(data) =>
val resultData = if ((compareCv.strCv eq null) && (compareCv.optStrCv eq null)) {
data
} else if (!(compareCv.strCv eq null)) {
data.copy(eq = data.eq.map(compareCv.strCv.to).filterNot(_.isEmpty).map(compareCv.strCv.from))
} else {
data.copy(eq = data.eq.map(compareCv.optStrCv.to).map(_.filterNot(_.isEmpty)).filterNot(_.isEmpty).map(compareCv.optStrCv.from))
}
set(resultData)
case _ =>
emptyValue[jsonReader.DataType]
}
case None =>
emptyValue[jsonReader.DataType]
}
}
tran: (Map[String, Json] => FAtomicValue)
}
}.aa
} { readlerList =>
{ sourceData: Map[String, Json] =>
readlerList.map(_.apply(sourceData))
}
}
}
示例13: toContent
//设置package包名称以及导入依赖的类
package net.scalax.fsn.parameter.atomic
import io.circe.{ Encoder, Json }
import scala.concurrent.{ ExecutionContext, Future }
import io.circe.generic.auto._
import io.circe.syntax._
trait FCompAbs {
self =>
type ParamType
val extParam: ParamType
val encoder: Encoder[ParamType]
val componentName: String
val compData: Future[Json]
def toContent(key: String)(implicit ec: ExecutionContext): Future[CompContentAbs] = {
compData.map { s =>
CompContent(key, self.componentName, self.extParam, s)(self.encoder)
}
}
}
trait CompContentAbs {
type ParamType
val extParam: ParamType
val encoder: Encoder[ParamType]
val compKey: String
val compName: String
val data: Json
def toDataJson: Json = {
implicit val jsonDataEncoder = this.encoder
CompContent(compKey, compName, extParam, data)(encoder).asJson
}
}
case class CompContent[T](compKey: String, compName: String, extParam: T, data: Json)(implicit val encoder: Encoder[T]) extends CompContentAbs {
override type ParamType = T
}
trait DataMapGen[P] {
def apply(s: P): List[Future[CompContentAbs]]
}
示例14: Sample03
//设置package包名称以及导入依赖的类
package net.scalax.fsn.database.test
import io.circe.Json
import io.circe.syntax._
import scala.concurrent.ExecutionContext.Implicits.global
import slick.jdbc.H2Profile.api._
object Sample03 {
def toJSON(query: Query[FriendTable, FriendTable#TableElementType, Seq]): DBIO[Seq[Map[String, Json]]] = {
query.map { s =>
(s.name, s.grade, s.age)
}.result.map { list =>
list.map { s =>
Map(
"name" -> s._1.asJson,
"grade" -> s._2.asJson,
"age" -> s._3.asJson
)
}
}
}
}
示例15: Api
//设置package包名称以及导入依赖的类
package feedbin
import Config.config
import io.circe.Json
import io.circe.generic.auto._
import io.circe.parser.parse
import io.circe.syntax._
import scala.language.postfixOps
import scalaj.http.{Http, HttpRequest}
object Api {
private val cfg = config match {
case Right(c) => c
case Left(e) =>
throw new Exception(e.messages.mkString("\n"))
}
private def request(endPoint: String): HttpRequest =
Http("https://api.feedbin.com/v2/" + endPoint)
.auth(cfg.email, cfg.password)
.timeout(connTimeoutMs = cfg.connectionTimeout, readTimeoutMs = cfg.readTimeout)
private def postJson(endPoint: String, data: Json): HttpRequest =
request(endPoint)
.postData(data.toString)
.header("content-type", "application/json")
def subscribe(feed_url: String): Option[Subscription] = {
val data = Json.obj("feed_url" -> feed_url.asJson)
val response = postJson("subscriptions.json", data).asString
parse(response.body).flatMap(_.as[Subscription]).toOption
}
}