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

Scala Json类代码示例

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

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



在下文中一共展示了Json类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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))
  }
} 
开发者ID:ulasakdeniz,项目名称:hakker,代码行数:58,代码来源:Controller.scala


示例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)
} 
开发者ID:ryanmiville,项目名称:akkord,代码行数:55,代码来源:PayloadParser.scala


示例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)
} 
开发者ID:Lasering,项目名称:http4s-akka,代码行数:21,代码来源:FrameFormatter.scala


示例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))
    }
  }
} 
开发者ID:felixbr,项目名称:swagger-blocks-scala,代码行数:27,代码来源:SpecEncoders.scala


示例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)
  }
} 
开发者ID:outr,项目名称:scarango,代码行数:61,代码来源:ArangoCursor.scala


示例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) 
开发者ID:outr,项目名称:scarango,代码行数:19,代码来源:QueryRequest.scala


示例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))
  }
} 
开发者ID:ergoplatform,项目名称:ergo,代码行数:57,代码来源:ADProof.scala


示例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())
  }
} 
开发者ID:ergoplatform,项目名称:ergo,代码行数:61,代码来源:BlockTransactions.scala


示例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)
  }
} 
开发者ID:ergoplatform,项目名称:ergo,代码行数:51,代码来源:AnyoneCanSpendNoncedBox.scala


示例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=")
  }
} 
开发者ID:m-doc,项目名称:common-model,代码行数:26,代码来源:CirceSpec.scala


示例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
) 
开发者ID:buildo,项目名称:wiro,代码行数:22,代码来源:models.scala


示例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))
    }
  }

} 
开发者ID:scalax,项目名称:ubw,代码行数:48,代码来源:SlickCompareOperation.scala


示例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]]
} 
开发者ID:scalax,项目名称:ubw,代码行数:49,代码来源:FCompAbs.scala


示例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
        )
      }
    }
  }

} 
开发者ID:scalax,项目名称:ubw,代码行数:26,代码来源:Sample03.scala


示例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
  }
} 
开发者ID:jarrodwb,项目名称:feedbin,代码行数:37,代码来源:Api.scala


示例16: Account

//设置package包名称以及导入依赖的类
package com.outr.stripe.connect

import com.outr.stripe.StripeList
import io.circe.Json

case class Account(id: String,
                   `object`: String,
                   businessLogo: Option[String],
                   businessName: String,
                   businessPrimaryColor: Option[String],
                   businessUrl: Option[String],
                   chargesEnabled: Boolean,
                   country: String,
                   debitNegativeBalances: Boolean,
                   declineChargesOn: DeclineChargesOn,
                   defaultCurrency: String,
                   detailsSubmitted: Boolean,
                   displayName: String,
                   email: String,
                   externalAccounts: StripeList[Json],
                   legalEntity: LegalEntity,
                   managed: Boolean,
                   metadata: Map[String, String],
                   productDescription: String,
                   statementDescriptor: String,
                   supportEmail: Option[String],
                   supportPhone: Option[String],
                   supportUrl: Option[String],
                   timezone: String,
                   tosAcceptance: Acceptance,
                   transferSchedule: TransferSchedule,
                   transferStatementDescriptor: Option[String],
                   transfersEnabled: Boolean,
                   verification: AccountVerification,
                   keys: Option[Keys]) 
开发者ID:outr,项目名称:scala-stripe,代码行数:36,代码来源:Account.scala


示例17: fold

//设置package包名称以及导入依赖的类
package com.yannick_cw.elastic_indexer4s.elasticsearch.elasic_config

import com.sksamuel.elastic4s.analyzers.AnalyzerDefinition
import com.sksamuel.elastic4s.mappings.MappingDefinition
import io.circe.{Json, ParsingFailure}
import io.circe.parser.parse

sealed trait MappingSetting {
  def fold[A](typed: TypedMappingSetting => A, unsafe: StringMappingSetting => A): A
}

case class TypedMappingSetting(
  analyzer: List[AnalyzerDefinition] = List.empty,
  mappings: List[MappingDefinition] = List.empty,
  shards: Option[Int] = None,
  replicas: Option[Int] = None
)
  extends MappingSetting {
  def fold[A](typed: (TypedMappingSetting) => A, unsafe: (StringMappingSetting) => A): A = typed(this)
}
sealed abstract case class StringMappingSetting(source: Json) extends MappingSetting {
  def fold[A](typed: (TypedMappingSetting) => A, unsafe: (StringMappingSetting) => A): A = unsafe(this)
}
object StringMappingSetting {
  def unsafeString(source: String): Either[ParsingFailure, MappingSetting] =
    parse(source).map(json => new StringMappingSetting(json){})
} 
开发者ID:yannick-cw,项目名称:elastic-indexer4s,代码行数:28,代码来源:MappingSetting.scala


示例18: CfExp

//设置package包名称以及导入依赖的类
package com.timeout.scalacloudformation

import java.time.{Duration, ZonedDateTime}

import io.circe.Json

trait CfExp[+T]

object CfExp {
  type E[+T] = CfExp[T]

  trait IsLit[A]

  object IsLit {
    implicit val stringLit: IsLit[String] = new IsLit[String] {}
    implicit val IntLit: IsLit[Int] = new IsLit[Int] {}
    implicit val longLit: IsLit[Long] = new IsLit[Long] {}
    implicit val doubleLit: IsLit[Double] = new IsLit[Double] {}
    implicit val boolLit: IsLit[Boolean] = new IsLit[Boolean] {}
    implicit val dateTimeLit: IsLit[ZonedDateTime] = new IsLit[ZonedDateTime] {}
    implicit val jsonLit: IsLit[Json] = new IsLit[Json] {}
    implicit val durationLit: IsLit[Duration] = new IsLit[Duration] {}
    implicit def propertyLit[T <: ResourceProperty]: IsLit[T] = new IsLit[T] {}
    implicit def listLit[A: IsLit]: IsLit[List[A]] = new IsLit[List[A]]{}
  }

  case class Lit[T: IsLit](value: T) extends E[T]

  
  case class ResourceRef(value: Resource) extends E[String]
  case class ParameterRef(value: Parameter) extends E[String]
  case class PseudoParameterRef(value: PseudoParameter) extends E[String]

  case class FnBase64(exp: E[String]) extends E[String]

  case class FnAnd(cond1: E[Boolean], cond2: E[Boolean]) extends E[Boolean]
  case class FnEquals[T](left: E[T], right: E[T]) extends E[Boolean]
  case class FnIf[T](cond: E[Boolean], ifTrue: E[T], ifFalse: E[T]) extends E[T]
  case class FnNot(cond: E[Boolean]) extends E[Boolean]
  case class FnOr(conds: E[Boolean]*) extends E[Boolean]
} 
开发者ID:typeformation,项目名称:typeformation,代码行数:42,代码来源:CfExp.scala


示例19: logicalId

//设置package包名称以及导入依赖的类
package com.timeout

import java.time.Duration

import io.circe.Json
import enum.Enum

package object scalacloudformation {
  trait ResourceProperty

  trait HasLogicalId {
    def logicalId: String
  }

  object ResourceAttributes {
    case class ResourceSignal(Count: CfExp[Int],
                              Timeout: CfExp[Duration])

    case class AutoscalingCreationPolicy(MinSuccessfulInstancesPercent: CfExp[Int])

    case class CreationPolicy(AutoscalingCreationPolicy: Option[AutoscalingCreationPolicy] = None,
                              ResourceSignal: Option[ResourceSignal] = None) extends ResourceProperty

    sealed trait DeletionPolicy extends ResourceProperty
    object DeletionPolicy {
      case object Delete extends DeletionPolicy
      case object Retain extends DeletionPolicy
      case object Snapshot extends DeletionPolicy

      implicit val enum: Enum[DeletionPolicy] = Enum.derived[DeletionPolicy]
    }

    case class AutoScalingReplacingUpdate(WillReplace: CfExp[Boolean])
    case class AutoScalingRollingUpdate(MaxBatchSize: Option[CfExp[Int]] = None,
                                        MinInstancesInService: Option[CfExp[Int]] = None,
                                        MinSuccessfulInstancesPercent: Option[CfExp[Int]] = None,
                                        PauseTime: Option[CfExp[Duration]] = None,
                                        WaitOnResourceSignals: Option[Boolean])
    case class AutoScalingScheduledAction(IgnoreUnmodifiedGroupSizeProperties: CfExp[Boolean])

    case class UpdatePolicy(AutoScalingReplacingUpdate: Option[AutoScalingReplacingUpdate] = None,
                            AutoScalingRollingUpdate: Option[AutoScalingRollingUpdate] = None,
                            AutoScalingScheduledAction: Option[AutoScalingScheduledAction] = None) extends ResourceProperty
  }



  trait Resource extends HasLogicalId {
    def fqn: String
    def logicalId: String
    def DependsOn: Option[Resource]
    def UpdatePolicy: Option[ResourceAttributes.UpdatePolicy]
    def DeletionPolicy: Option[ResourceAttributes.DeletionPolicy]
    def CreationPolicy: Option[ResourceAttributes.CreationPolicy]
    def jsonEncode: Json
  }

  case class Tag(key: String, value: String)
} 
开发者ID:typeformation,项目名称:typeformation,代码行数:60,代码来源:package.scala


示例20: GCMMessage

//设置package包名称以及导入依赖的类
package io.grhodes.mcm.server.gcm

import io.circe.{Cursor, Json}
import io.circe.jawn._
import org.apache.vysper.xml.fragment.{XMLElement, XMLElementBuilder}
import org.apache.vysper.xmpp.stanza.Stanza

import scala.collection.JavaConverters._

case class GCMMessage(element: XMLElement) {
  def getJsonObject: Cursor = parse(element.getSingleInnerText.getText).getOrElse(Json.Null).cursor
}
object GCMMessage {
  def fromStanza(stanza: Stanza) = {
    val xElms = stanza.getInnerElementsNamed(Constants.ELEMENT_NAME)
    val xElm = xElms.asScala.find(elm => elm.getNamespaceURI != null && elm.getNamespaceURI.startsWith(Constants.NAMESPACE))
    xElm.map(new GCMMessage(_)).orNull
  }

  class Builder extends XMLElementBuilder(Constants.ELEMENT_NAME, Constants.NAMESPACE)

} 
开发者ID:grahamar,项目名称:mcm-server,代码行数:23,代码来源:GCMMessage.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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