当前位置: 首页>>代码示例>>Scala>>正文


Scala Printer类代码示例

本文整理汇总了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")
  }

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

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

示例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 
开发者ID:travisbrown,项目名称:circe-spray,代码行数:50,代码来源:JsonSupport.scala

示例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)
} 
开发者ID:aishfenton,项目名称:Argus,代码行数:48,代码来源:JsonDiff.scala

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

示例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])
  }
} 
开发者ID:iwaisman,项目名称:json_api-scala,代码行数:28,代码来源:AkkaInstances.scala

示例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)
} 
开发者ID:msilb,项目名称:scalanda-v20,代码行数:36,代码来源:AkkaHttpCirceSupport.scala

示例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 = "")
} 
开发者ID:yunify,项目名称:qingstor-sdk-scala,代码行数:46,代码来源:QSConstants.scala

示例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"
} 
开发者ID:wslulciuc,项目名称:mockingbird,代码行数:57,代码来源:streams.scala

示例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)
        }
      }
  }
} 
开发者ID:Be-ngt-oH,项目名称:TeSSLaSim,代码行数:35,代码来源:SimulatorService.scala


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