本文整理汇总了Scala中io.circe.Printer类的典型用法代码示例。如果您正苦于以下问题:Scala Printer类的具体用法?Scala Printer怎么用?Scala Printer使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Printer类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: Helper
//设置package包名称以及导入依赖的类
package net.scalax.fsn.database.test
import io.circe.Printer
import net.scalax.fsn.database.test.Sample01.{ friend1, friend2, friend3, friend4 }
import net.scalax.fsn.slick.model.JsonView
import org.h2.jdbcx.JdbcDataSource
import slick.jdbc.H2Profile.api._
import io.circe.syntax._
import io.circe.generic.auto._
object Helper {
lazy val db = {
val datasource = new JdbcDataSource()
datasource.setUrl(s"jdbc:h2:mem:commonSlick;DB_CLOSE_DELAY=-1")
Database.forDataSource(datasource, None)
}
def initData: DBIO[Unit] = {
FriendTable.schema.create >> (FriendTable ++= List(friend1, friend2, friend3, friend4)) >> DBIO.successful(())
}
val printer = Printer(
preserveOrder = true,
dropNullKeys = false,
indent = " ",
lbraceRight = " ",
rbraceLeft = " ",
lbracketRight = "\n",
rbracketLeft = "\n",
lrbracketsEmpty = "\n",
arrayCommaRight = "\n",
objectCommaRight = " ",
colonLeft = " ",
colonRight = " "
)
def prettyPrint(view: JsonView): Unit = {
println("json data:\n" + view.data.asJson.pretty(printer) + "\n")
println("properties:\n" + view.properties.asJson.pretty(printer) + "\n")
}
}
示例2: print
//设置package包名称以及导入依赖的类
package io.rout
import io.circe.{Json, Printer}
import io.circe.jackson._
package object circe extends Encoders with Decoders{
protected def print(json: Json): String = Printer.noSpaces.pretty(json)
object dropNullKeys extends Encoders with Decoders{
private val printer: Printer = Printer.noSpaces.copy(dropNullKeys = true)
protected def print(json: Json): String = printer.pretty(json)
}
object jacksonSerializer extends Encoders with Decoders{
protected def print(json: Json): String = jacksonPrint(json)
}
}
示例3: printer
//设置package包名称以及导入依赖的类
package io.circe.spray
import cats.data.Validated
import io.circe.{ Errors, Printer, RootEncoder }
import io.circe.jawn._
import spray.http.{ ContentTypes, HttpCharsets, HttpEntity, MediaTypes }
import spray.httpx.marshalling.Marshaller
import spray.httpx.unmarshalling.Unmarshaller
trait JsonSupport {
def printer: Printer
implicit final def circeJsonMarshaller[A](implicit encoder: RootEncoder[A]): Marshaller[A] =
Marshaller.delegate[A, String](ContentTypes.`application/json`) { value =>
printer.pretty(encoder(value))
}
implicit def circeJsonUnmarshaller[A](implicit decoder: RootDecoder[A]): Unmarshaller[A]
}
trait FailFastUnmarshaller { this: JsonSupport =>
implicit final def circeJsonUnmarshaller[A](implicit decoder: RootDecoder[A]): Unmarshaller[A] =
Unmarshaller[A](MediaTypes.`application/json`) {
case x: HttpEntity.NonEmpty =>
decode[A](x.asString(defaultCharset = HttpCharsets.`UTF-8`))(decoder.underlying) match {
case Right(a) => a
case Left(e) => throw e
}
}
}
trait ErrorAccumulatingUnmarshaller { this: JsonSupport =>
implicit final def circeJsonUnmarshaller[A](implicit decoder: RootDecoder[A]): Unmarshaller[A] =
Unmarshaller[A](MediaTypes.`application/json`) {
case x: HttpEntity.NonEmpty =>
decodeAccumulating[A](x.asString(defaultCharset = HttpCharsets.`UTF-8`))(decoder.underlying) match {
case Validated.Valid(result) => result
case Validated.Invalid(errors) => throw Errors(errors)
}
}
}
trait NoSpacesPrinter { this: JsonSupport =>
final def printer: Printer = Printer.noSpaces
}
final object JsonSupport extends JsonSupport with NoSpacesPrinter with FailFastUnmarshaller
final object ErrorAccumulatingJsonSupport extends JsonSupport with NoSpacesPrinter with ErrorAccumulatingUnmarshaller
示例4: JsonDiff
//设置package包名称以及导入依赖的类
package argus.json
import io.circe.Json
import io.circe.Printer
object JsonDiff {
def diff(j1: Json, j2: Json) = {
val removeNulls = (t: (String, Json)) => { !t._2.isNull }
def diffR(j1: Json, j2: Json): List[(String, String)] = {
(j1.asObject, j2.asObject) match {
case (Some(o1), Some(o2)) => {
val o1m = o1.toMap.filter(removeNulls)
val o2m = o2.toMap.filter(removeNulls)
val sharedKeys = o1m.keySet intersect o2m.keySet
// First record any missing fields
val diffKeys =
(o1m.keySet diff sharedKeys).map((_, "missing")) ++
(o2m.keySet diff sharedKeys).map(("missing", _))
// Now recurse on each field
diffKeys.toList ++ sharedKeys.foldLeft(List[(String, String)]()) {
case(accum, k) => accum ++ diffR(o1(k).get, o2(k).get)
}
}
case _ => {
(j1.asArray, j2.asArray) match {
case (Some(a1), Some(a2)) => {
a1.zip(a2).flatMap { case(jj1, jj2) => diffR(jj1,jj2) } toList
}
// Everything else
case _ => if (j1 != j2) List((j1.toString, j2.toString)) else Nil
}
}
}
}
diffR(j1, j2)
}
val NoNullPrinter = Printer.spaces2.copy(dropNullKeys = true)
}
示例5: jsonDecoderOf
//设置package包名称以及导入依赖的类
package org.scalaexercises.evaluator
import org.http4s._, org.http4s.dsl._
import io.circe.{Decoder, Encoder, Json, Printer}
import org.http4s.headers.`Content-Type`
import io.circe.jawn.CirceSupportParser.facade
trait Http4sCodecInstances {
implicit val jsonDecoder: EntityDecoder[Json] = jawn.jawnDecoder(facade)
implicit def jsonDecoderOf[A](implicit decoder: Decoder[A]): EntityDecoder[A] =
jsonDecoder.flatMapR { json =>
decoder
.decodeJson(json)
.fold(
failure =>
DecodeResult.failure(
InvalidMessageBodyFailure(s"Could not decode JSON: $json", Some(failure))),
DecodeResult.success(_)
)
}
implicit val jsonEntityEncoder: EntityEncoder[Json] = EntityEncoder[String]
.contramap[Json] { json =>
Printer.noSpaces.pretty(json)
}
.withContentType(`Content-Type`(MediaType.`application/json`))
implicit def jsonEncoderOf[A](implicit encoder: Encoder[A]): EntityEncoder[A] =
jsonEntityEncoder.contramap[A](encoder.apply)
}
object codecs extends Http4sCodecInstances
示例6: __AkkaInstances
//设置package包名称以及导入依赖的类
package org.twistednoodle.json_api.integrations.circe
import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller}
import akka.http.scaladsl.model.MediaTypes._
import akka.http.scaladsl.unmarshalling.Unmarshaller
import io.circe.syntax._
import io.circe.{Json, Printer, parser}
// Created by iwaisman on 12/30/16.
trait AkkaInstances { self: CirceApi =>
private[circe] object __AkkaInstances {
// Printers
final val noSpacesNoNulls = Printer.noSpaces.copy(dropNullKeys = true)
final val spaces4NoNulls = Printer.spaces4.copy(dropNullKeys = true)
implicit def circeDocumentMarshaller(implicit printer: Json => String = noSpacesNoNulls.pretty): ToEntityMarshaller[JsonApiDocument] =
Marshaller.StringMarshaller.wrap(`application/vnd.api+json`)(doc => printer(doc.asJson))
implicit val circeDocumentUnmarshaller = Unmarshaller.
stringUnmarshaller.
forContentTypes(`application/vnd.api+json`, `application/json`).
map(parser.decode[JsonApiDocument])
}
}
示例7: AkkaHttpCirceSupport
//设置package包名称以及导入依赖的类
package com.msilb.scalandav20.common
import akka.http.scaladsl.marshalling.{ Marshaller, ToEntityMarshaller }
import akka.http.scaladsl.model.MediaTypes.`application/json`
import akka.http.scaladsl.unmarshalling.{
FromEntityUnmarshaller,
Unmarshaller
}
import akka.util.ByteString
import io.circe.{ Decoder, Encoder, Json, Printer, jawn }
object AkkaHttpCirceSupport extends AkkaHttpCirceSupport
trait AkkaHttpCirceSupport {
private val jsonStringUnmarshaller =
Unmarshaller.byteStringUnmarshaller
.forContentTypes(`application/json`)
.mapWithCharset {
case (ByteString.empty, _) => throw Unmarshaller.NoContentException
case (data, charset) => data.decodeString(charset.nioCharset.name)
}
private val jsonStringMarshaller =
Marshaller.stringMarshaller(`application/json`)
implicit def circeUnmarshaller[A](
implicit decoder: Decoder[A]
): FromEntityUnmarshaller[A] =
jsonStringUnmarshaller.map(jawn.decode(_).fold(throw _, identity))
implicit def circeToEntityMarshaller[A](implicit encoder: Encoder[A],
printer: Json => String = Printer.noSpaces.copy(dropNullKeys = true).pretty): ToEntityMarshaller[A] =
jsonStringMarshaller.compose(printer).compose(encoder.apply)
}
示例8: QSConstants
//设置package包名称以及导入依赖的类
package com.qingstor.sdk.constant
import akka.actor.ActorSystem
import io.circe.Printer
import scala.io.Source
object QSConstants {
private def getSDKVersion: String = {
val pattern = """(?<!\\)(\"|\')(.*?)(?<!\\)\1""".r
val versionLine = Source.fromFile("build.sbt").getLines().find(_.startsWith("version := ")).getOrElse("")
pattern.findFirstIn(versionLine).getOrElse("").replace("\"", "")
}
private val scalaVersion: String = util.Properties.versionNumberString
private val osName: String = util.Properties.osName
private val arch: String = System.getProperty("os.arch")
final val QingStorSystem: ActorSystem = ActorSystem("QingStor")
val LogFatal: String = "fatal"
val LogError: String = "error"
val LogWarn: String = "warn"
val LogDebug: String = "debug"
val LogInfo: String = "info"
final val ParamsLocationHeader = "headers"
final val ParamsLocationParam = "params"
final val ParamsLocationElement = "elements"
final val ParamsLocationBody = "body"
val APIGETService: String = "GET Service"
val ACLPermissions = List("READ", "WRITE", "FULL_CONTROL")
val GranteeTypes = List("user", "group")
val CORSHttpMethods = List("GET", "PUT", "POST", "DELETE", "HEAD")
val StatementEffects = List("allow", "deny")
val BucketNamePlaceHolder: String = "{bucketName}"
val ObjectKeyPlaceHolder: String = "{objectKey}"
val UserAgent: String = s"qingstor-sdk-scala/$getSDKVersion (Scala $scalaVersion; $osName $arch)"
val printer = Printer(preserveOrder = true, dropNullKeys = true, indent = "")
}
示例9: PartitionKey
//设置package包名称以及导入依赖的类
package mockingbird
import io.circe.Printer
import io.circe.syntax._
import java.nio.ByteBuffer
import org.apache.avro.Schema
import scala.concurrent.ExecutionContext
import scala.concurrent.Future
case class PartitionKey(value: String)
case class Record(key: Record.Key, bytes: ByteBuffer)
object Record {
case class Key(value: String) {
override def toString = value
}
def apply(data: EnrichedSensorData): Record = {
Record(key = Key(data.device_id.asString),
bytes = Printer.noSpaces.prettyByteBuffer(data.asJson))
}
}
sealed trait DataStream {
type S <: Schema
val schema: S
val name: String
def add(rec: Record)(implicit ec: ExecutionContext): Future[Record] =
Future {
???
}
def add(recs: Seq[Record])(implicit ec: ExecutionContext): Future[Seq[Record]] =
Future {
???
}
}
object DataStream {
def apply(name: String): Option[DataStream] = name match {
case SensorStream.name => Some(SensorStream)
case StatsStream.name => Some(StatsStream)
case _ => None
}
}
object SensorStream extends DataStream {
type S = Schema
val schema = ???
val name = "sensor"
}
object StatsStream extends DataStream {
type S = Schema
val schema = ???
val name = "stats"
}
示例10: SimulatorService
//设置package包名称以及导入依赖的类
package tesslasimulator.webService
import io.circe.{Printer, Decoder, Encoder}
import io.circe.generic.auto._
import org.http4s.HttpService
import org.http4s.circe
import org.http4s.dsl._
import tesslasimulator.simulator.Simulator
import tesslasimulator.shared.StreamJsonCodec._
import ExtendedJsonCodec._
object SimulatorService {
implicit def circeJsonDecoder[A](implicit decoder: Decoder[A]) = circe.jsonOf[A]
implicit def circeJsonEncoder[A](implicit encoder: Encoder[A]) = circe.jsonEncoderWithPrinterOf[A](Printer.spaces2)
case class SimulateRequest(scenarioSpec: String, tesslaSpec: String)
val service = HttpService {
case GET -> Root => Ok("Hello World!")
case [email protected] -> Root / "simulate" =>
req.decodeStrict[SimulateRequest] { request =>
try {
Simulator.simulate(request.scenarioSpec, request.tesslaSpec) match {
case Left(streams) => Ok(Map("streams" -> streams))
case Right(errors) => Ok(Map("errors" -> errors))
}
} catch {
case e: Exception => InternalServerError(e.getClass.getCanonicalName)
}
}
}
}