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


Scala Serialization类代码示例

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


在下文中一共展示了Serialization类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: EventDeserialiser

//设置package包名称以及导入依赖的类
package serialisation

import java.util

import model.Event
import org.apache.kafka.common.serialization.{Deserializer, StringDeserializer}
import org.json4s.native.Serialization
import org.json4s.native.Serialization.read
import org.json4s.{Formats, NoTypeHints}

class EventDeserialiser extends Deserializer[Event] {

  implicit val formats: Formats = Serialization.formats(NoTypeHints)

  val stringDeserialiser = new StringDeserializer

  override def configure(configs: util.Map[String, _], isKey: Boolean): Unit = {
    stringDeserialiser.configure(configs, isKey)
  }

  override def deserialize(topic: String, data: Array[Byte]): Event = {
    val stringValue = stringDeserialiser.deserialize(topic, data)
    read[Event](stringValue)
  }

  override def close(): Unit = {
    stringDeserialiser.close()
  }
} 
开发者ID:benwheeler,项目名称:kafka-streams-poc,代码行数:30,代码来源:EventDeserialiser.scala

示例2: EventSerialiser

//设置package包名称以及导入依赖的类
package serialisation

import java.util

import model.Event
import org.apache.kafka.common.serialization.{Serializer, StringSerializer}
import org.json4s.native.Serialization
import org.json4s.native.Serialization.write
import org.json4s.{Formats, NoTypeHints}

class EventSerialiser extends Serializer[Event] {

  implicit val formats: Formats = Serialization.formats(NoTypeHints)

  val stringSerialiser = new StringSerializer

  override def configure(configs: util.Map[String, _], isKey: Boolean): Unit = {
    stringSerialiser.configure(configs, isKey)
  }

  override def serialize(topic: String, data: Event): Array[Byte] = {
    val stringValue = write(data)
    stringSerialiser.serialize(topic, stringValue)
  }

  override def close(): Unit = {
    stringSerialiser.close()
  }
} 
开发者ID:benwheeler,项目名称:kafka-streams-poc,代码行数:30,代码来源:EventSerialiser.scala

示例3: StringEventCollector

//设置package包名称以及导入依赖的类
package transformation

import model.Event
import org.apache.kafka.streams.KeyValue
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
import org.json4s.{Formats, NoTypeHints}

class StringEventCollector(storeName: String)
  extends CollectTransformer[String, String, String, String, String](storeName) {

  implicit val formats: Formats = Serialization.formats(NoTypeHints)

  override def appendToStore(storeValue: String, appendValue: String): String = {
    appendValue
  }

  override def collectComplete(storeValue: String, appendValue: String): Boolean = {
    // just merges two events
    storeValue.nonEmpty && appendValue.nonEmpty
  }

  override def collectOutput(inputKey: String, storeValue: String, mergeValue: String): KeyValue[String, String] = {
    new KeyValue(inputKey, collect(storeValue, mergeValue))
  }

  def collect(storeValue: String, mergeValue: String): String = {
    log.info(s"Collecting ...")
    log.info(s"   with store : $storeValue")
    log.info(s"   with event : $mergeValue")
    val firstEvent = read[Event](storeValue)
    val secondEvent = read[Event](mergeValue)
    write(Event(firstEvent.eventType + secondEvent.eventType,
      firstEvent.count + secondEvent.count,
      firstEvent.name + secondEvent.name))
  }
} 
开发者ID:benwheeler,项目名称:kafka-streams-poc,代码行数:38,代码来源:StringEventCollector.scala

示例4: StripeAdditionalInfoMapper

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


import com.wix.pay.creditcard.{AddressDetailed, CreditCard}
import com.wix.pay.model._
import org.json4s.native.Serialization


class StripeAdditionalInfoMapper {

  def createMap(creditCard: CreditCard, customer: Option[Customer], deal: Option[Deal]): MappedParams = {
    val params = new MappedParams()

    creditCard.billingAddressDetailed.foreach(address => params.put("Billing Address", valueOf(address)))
    customer.foreach(customer => params.put("Customer", valueOf(customer)))

    deal.foreach(deal => extractInvoiceIdFrom(deal, intoParams = params))
    deal.foreach(deal => extractShippingAddressFrom(deal, intoParams = params))
    deal.foreach(deal => extractOrderItemsFrom(deal, intoParams = params))
    deal.foreach(deal => extractIncludedChargesFrom(deal, intoParams = params))

    params
  }

  private def valueOf(customer: Customer) = {
    Serialization.write(customer).adjustToStripeRequirements()
  }

  private def valueOf(billingAddress: AddressDetailed) = {
    Serialization.write(billingAddress).adjustToStripeRequirements()
  }

  private def extractInvoiceIdFrom(deal: Deal, intoParams: MappedParams) = {
    deal.invoiceId.foreach(id => intoParams.put("Invoice Id", id))
  }

  private def extractShippingAddressFrom(deal: Deal, intoParams: MappedParams): Unit = {
    deal.shippingAddress.foreach(address => intoParams.put("Shipping Address", valueOf(address)))
  }

  private def valueOf(shippingAddress: ShippingAddress) = {
    Serialization.write(shippingAddress).adjustToStripeRequirements()
  }

  private def extractOrderItemsFrom(deal: Deal, intoParams: MappedParams) = {
    if (deal.orderItems.nonEmpty)
      intoParams.put("Order Items", valueOf(deal.orderItems))
  }

  private def valueOf(orderItems: Seq[OrderItem]) = {
    Serialization.write(orderItems).adjustToStripeRequirements()
  }

  private def extractIncludedChargesFrom(deal: Deal, intoParams: MappedParams): Unit = {
    deal.includedCharges.foreach(includedCharges => intoParams.put("Included Charges", valueOf(includedCharges)))
  }

  private def valueOf(includedCharges: IncludedCharges) = {
    Serialization.write(includedCharges).adjustToStripeRequirements()
  }
} 
开发者ID:wix,项目名称:libpay-stripe,代码行数:62,代码来源:StripeAdditionalInfoMapper.scala

示例5: SerializationTest

//设置package包名称以及导入依赖的类
package org.argus.amandroid.serialization

import java.io.{FileReader, FileWriter}

import org.argus.amandroid.alir.componentSummary.ApkYard
import org.argus.amandroid.core.decompile.{ConverterUtil, DecompileLayout, DecompileStrategy, DecompilerSettings}
import org.argus.amandroid.core.model.ApkModel
import org.argus.jawa.core.DefaultReporter
import org.json4s.NoTypeHints
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
import org.scalatest.{FlatSpec, Matchers}
import org.argus.jawa.core.util.FileUtil


class SerializationTest extends FlatSpec with Matchers {

  "ApkModel" should "successfully serialized and deserialized" in {
    val apkFile = getClass.getResource("/icc-bench/IccHandling/icc_explicit_src_sink.apk").getPath
    val apkUri = FileUtil.toUri(apkFile)
    val outputUri = FileUtil.toUri(apkFile.substring(0, apkFile.length - 4))
    val reporter = new DefaultReporter
    val yard = new ApkYard(reporter)
    val layout = DecompileLayout(outputUri)
    val strategy = DecompileStrategy(layout)
    val settings = DecompilerSettings(debugMode = false, forceDelete = true, strategy, reporter)
    val apk = yard.loadApk(apkUri, settings, collectInfo = true)
    val model = apk.model
    implicit val formats = Serialization.formats(NoTypeHints) + ApkModelSerializer
    val apkRes = FileUtil.toFile(FileUtil.appendFileName(outputUri, "apk.json"))
    val oapk = new FileWriter(apkRes)
    try {
      write(model, oapk)
    } catch {
      case e: Exception =>
        e.printStackTrace()
    } finally {
      oapk.flush()
      oapk.close()
    }
    val iapk = new FileReader(apkRes)
    var newApkModel: ApkModel = null
    try {
      newApkModel = read[ApkModel](iapk)
    } catch {
      case e: Exception =>
        e.printStackTrace()
    } finally {
      iapk.close()
      ConverterUtil.cleanDir(outputUri)
    }
    require(
      model.getAppName == newApkModel.getAppName &&
      model.getComponents == newApkModel.getComponents &&
      model.getLayoutControls == newApkModel.getLayoutControls &&
      model.getCallbackMethods == newApkModel.getCallbackMethods &&
      model.getComponentInfos == newApkModel.getComponentInfos &&
      model.getEnvMap == newApkModel.getEnvMap)
  }
} 
开发者ID:arguslab,项目名称:Argus-SAF,代码行数:61,代码来源:SerializationTest.scala

示例6: Benchmarks

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

import com.vatbox.polyjuice.internal.PolyjuiceMapper
import generators.Generator
import org.json4s.native.Serialization
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.time.{Millis, Minutes, Span}
import org.scalatest.{FreeSpec, Matchers, OptionValues, TryValues}

import scala.concurrent.ExecutionContext.Implicits.global

class Benchmarks extends FreeSpec with TryValues with OptionValues with Matchers with ScalaFutures with GeneratorDrivenPropertyChecks {
  implicit val formats = org.json4s.DefaultFormats
  val amount = 10000
  override implicit val patienceConfig = PatienceConfig(Span(1, Minutes), Span(10, Millis))
  val mapper: PolyjuiceMapper = Polyjuice.createMapper(varName = "model", userCode = s"""if (model.bool) return model.int; else return model.str;""")
  "Map many" in {
    forAll(Generator.modelGen, minSuccessful(amount)) { model =>
      val json = Serialization.write(model)
      if (model.bool) {
        val result = mapper.map[Int](json).futureValue.get
        assert(result === model.int)
      }
      else {
        val result = mapper.map[String](json).futureValue.get
        assert(result === model.str)
      }
    }
  }
} 
开发者ID:VATBox,项目名称:polyjuicelib,代码行数:32,代码来源:Benchmarks.scala

示例7: Person

//设置package包名称以及导入依赖的类
package com.github.shinharad.scalajsonlab.json4s

case class Person(
  id: Long,
  name: Option[String] = None,
  age: Option[Int] = None
)

object ExampleNative extends App {
  import org.json4s._
  import org.json4s.native.JsonMethods._
  import org.json4s.native.Serialization

  val personStr =
    """
      |{
      |  "id" : 111,
      |  "name" : "zzz",
      |  "age" : 222
      |}
    """.stripMargin

  implicit val formats = DefaultFormats
  val caseclass1: Person = parse(personStr).extract[Person]
  println(caseclass1)

  val str1: String = Serialization.write(caseclass1)
  println(str1)

  val caseclass2: Person = Person(123L)
  val str2: String = Serialization.write(caseclass2)
  println(str2)

}

object ExampleJackson extends App {
  import org.json4s._
  import org.json4s.jackson.JsonMethods._
  import org.json4s.jackson.Serialization

  val personStr =
    """
      |{
      |  "id" : 111,
      |  "name" : "zzz",
      |  "age" : 222
      |}
    """.stripMargin

  implicit val formats = DefaultFormats
  val caseclass1: Person = parse(personStr).extract[Person]
  println(caseclass1)

  val str1: String = Serialization.write(caseclass1)
  println(str1)

  val caseclass2: Person = Person(123L)
  val str2: String = Serialization.write(caseclass2)
  println(str2)

} 
开发者ID:shinharad,项目名称:scala-json-lab,代码行数:62,代码来源:Example.scala

示例8: SlackWebHookAppender

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

import ch.qos.logback.classic.spi.ILoggingEvent
import ch.qos.logback.core.Layout
import ch.qos.logback.core.LayoutBase
import ch.qos.logback.core.UnsynchronizedAppenderBase
import scalaj.http._
import org.json4s.DefaultFormats
import org.json4s.native.Serialization

class SlackWebHookAppender extends UnsynchronizedAppenderBase[ILoggingEvent]{
  implicit val formats = DefaultFormats

  private var channel: Option[String] = None
  private var webHookUrl: Option[String] = None
  private var username: Option[String] = None
  private var iconEmoji: Option[String] = None
  private var layout: Layout[ILoggingEvent]  = defaultLayout

  private def defaultLayout:Layout[ILoggingEvent] = new LayoutBase[ILoggingEvent]{
    def doLayout(event: ILoggingEvent) :String =
      s"-- [${event.getLevel}] - ${event.getFormattedMessage.replaceAll("\n", "\n\t")}"
  }

  override def append(evt: ILoggingEvent) = {
    val optResult = for {
      c <- channel
      w <- webHookUrl
    } yield {
      val attachment = Attachment(layout.doLayout(evt), "danger")
      val payload = Payload(c,
        username.getOrElse("Slack Logback Appender"),
        iconEmoji.getOrElse(":japanese_goblin:"),
        "Error detected!!",
        Some(Seq(attachment)))
      val res = Http(w).postForm(Seq("payload" -> Serialization.write(payload))).asString
      if(res.code == 200) Result.Success
      else Result.Failure(res.body.toString)
    }

    optResult.getOrElse(Result.Failure("channel or webHookUrl is not set")) match {
      case Result.Success => ()
      case Result.Failure(msg) =>
        val errorMessage = s"Error in Logback-Slack Web Hook Appender: $msg"
        new RuntimeException(errorMessage).printStackTrace
        addError(errorMessage)
    }

  }

  def setChannel(t: String) = { channel = Some(if(t.startsWith("#")) t else "#" + t) }
  def setWebHookUrl(w: String) = {webHookUrl = Some(w)}
  def setUsername(u: String) = {username = Some(u)}
  def setIconEmoji(i: String) = {
    val prefix = if(i.startsWith(":")) "" else ":"
    val suffix = if(i.endsWith(":")) "" else ":"
    iconEmoji = Some(prefix + i + suffix)
  }
  def setLayout(l: Layout[ILoggingEvent]) = {layout = l}
} 
开发者ID:yuki-mt,项目名称:logback-slack-webhook-appender,代码行数:61,代码来源:SlackWebhookAppender.scala

示例9: SingleCrystalSilicon

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

import org.json4s.ShortTypeHints
import org.json4s.native.Serialization
import org.json4s.native.Serialization._

trait Silicon

  case class SingleCrystalSilicon(grainSize: Int) extends Silicon

  case class MultiCrystalSilicon(name: String, grainSize: Int) extends Silicon

  object Silicon {
    val silicons = List[Silicon](
    MultiCrystalSilicon(name = "MultiCrystalline", grainSize = 10),
    MultiCrystalSilicon(name = "PolyCrystalline", grainSize = 1),
    SingleCrystalSilicon(grainSize = 1000)
    )

    private implicit val formats = Serialization.formats(ShortTypeHints(List(classOf[MultiCrystalSilicon], classOf[SingleCrystalSilicon])))
    def toJson(silicons: List[Silicon]): String = writePretty(silicons)
    def toJson(silicon: Silicon): String = writePretty(silicon)
  } 
开发者ID:ryadav88,项目名称:spray-tutorial,代码行数:24,代码来源:Silicon.scala

示例10: TnReaderTest

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

import org.json4s._
import org.json4s.native.Serialization
import com.bfm.topnotch.SparkApplicationTester
import org.scalatest.{Matchers, Tag}

/**
 * The tests for [[com.bfm.topnotch.tnengine.TnReader TnReader]].
  * Note that most testing is done by the tests for [[com.bfm.topnotch.tnengine.TnEngine TnEngine]]
 */
class TnReaderTest extends SparkApplicationTester with Matchers {

  object getReaderTag extends Tag("getReader")
  object readerVariableTag extends Tag("readerVariables")
  object jarReaderTag extends Tag("jarReader")
  implicit val formats = Serialization.formats(NoTypeHints)

  "getReader" should "throw an IllegalArgumentException when the plan doesn't exist" taggedAs(getReaderTag) in {
    intercept[IllegalArgumentException] {
      val fileReader = new TnFileReader
      fileReader.readConfiguration("src/test/resources/com/bfm/DOESNTEXIST")
    }
  }

  it should "replace variables in a configuration" taggedAs(readerVariableTag) in {
    val fileReader = new TnFileReader(Map("var1" -> "true", "var2" -> "false"))
    val replacedAST = fileReader.readConfiguration("src/test/resources/com/bfm/topnotch/tnengine/cliReplacementTest.json")
    replacedAST \ "trueToBeReplaced" should not equal(JNothing)
    (replacedAST \ "replaceThisValue").extract[String] should equal("false")
  }
} 
开发者ID:blackrock,项目名称:TopNotch,代码行数:33,代码来源:TnReaderTest.scala

示例11: Validator

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

import java.io.File

import com.avaglir.tauroneo.knn._
import com.avaglir.tauroneo.utils._
import com.github.tototoshi.csv._
import org.json4s._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.read

import scala.io.Source
import scala.util.Random

object Validator {
  implicit val formats = Serialization.formats(NoTypeHints)

  val rand = new Random
  val allData: Seq[FrameData] = {
    val d = new File("replay_data")
    d.listFiles.filter { f => f.isFile && f.getName != "all.json" } flatMap { f =>
      println(s"loading ${f.getName}")
      read[List[FrameData]]((Source fromFile f).reader)
    }
  }

  println(s"total of ${allData.size} features loaded")

  val seed = System.currentTimeMillis()
  val random = new Random(seed)

  val (trainingData, testingData) = allData partition { _ => rand.nextInt(10) <= 7 }

  def square(i: Int): Int = i * i

  def main(args: Array[String]): Unit = {
    implicit val milC: KnnFrameCompanion[MilFrame] = MilFrame
    implicit val econC: KnnFrameCompanion[EconFrame] = EconFrame

    val mil = execute(MilFrame).flatten
    val econ = execute(EconFrame).flatten

    writeOut[MilFrame](mil)
    writeOut[EconFrame](econ)
  }

  def execute[T <: KnnFrame](frameCompanion: KnnFrameCompanion[T]) = Stream.range(2, 11) map { k =>
    val reg = Reg(trainingData, frameCompanion, k)

    testingData.map(frameCompanion.apply).filter { elem => elem.magnitude > 500 }.map { elem => {
      (k, elem.score, reg.estimate(elem))
    } }.sorted
  }

  def writeOut[T <: KnnFrame: KnnFrameCompanion](vals: Seq[(Int, Int, Int)]) = {
    val writer = CSVWriter open s"validation/${implicitly[KnnFrameCompanion[T]].frameTypeName}.csv"
    writer.writeRow(List("k", "actual", "estimate"))
    vals foreach { elem => writer.writeRow(elem.productIterator.toSeq) }
    writer.close()
  }
} 
开发者ID:mammothbane,项目名称:tauroneo,代码行数:62,代码来源:Validator.scala

示例12: Ticket

//设置package包名称以及导入依赖的类
package com.octo.nad.handson.model

import org.json4s.NoTypeHints
import org.json4s.native.Serialization
import org.json4s.native.Serialization._


case class Ticket(
                   id_day:Int,
                   sid_store:Int,
                   id_basket:Int,
                   libelle_min:String,
                   id_client:Option[Int],
                   nb_articles:Int,
                   total_ticket:BigDecimal,
                   liste_produits:List[Produit]){
  def toJson = write(this)(Serialization.formats(NoTypeHints))
}
object Ticket{
  implicit val formats = Serialization.formats(NoTypeHints)
  def fromJson(str: String) = read[Ticket](str)
} 
开发者ID:tmouron,项目名称:hands-on-spark,代码行数:23,代码来源:Ticket.scala

示例13: generateProductsNumber

//设置package包名称以及导入依赖的类
package com.octo.nad.handson.producer

import java.text.SimpleDateFormat
import java.util.{Date, TimeZone}

import com.octo.nad.handson.model.Produit
import com.octo.nad.handson.model.Ticket

import scala.util.Random


  def generateProductsNumber = {
    val x = rand.nextDouble()
    (-89 * Math.pow(x,3) + 155 * Math.pow(x,2) - 105 * x + 40).toInt
  }

  def getListeMarches = {
    import org.json4s.NoTypeHints
    import org.json4s.native.Serialization
    import org.json4s.native.Serialization._
    implicit val formats = Serialization.formats(NoTypeHints)

    val stream = TicketsGenerator.getClass.getResourceAsStream("/sid_marche_list")
    val line = scala.io.Source.fromInputStream(stream).getLines().next()

    read[List[Int]](line)
  }
} 
开发者ID:tmouron,项目名称:hands-on-spark,代码行数:29,代码来源:TicketsGenerator.scala

示例14: ItemData

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

import org.json4s._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}

import akka.actor.Actor
import akka.actor.ActorRef
import akka.actor.FSM
import akka.actor.FSM._
import akka.actor.Props
import scala.collection.immutable.Queue

case class ItemData(val erpData: ERPData, val specData: SpecData, val prodData: Queue[_])

class Item extends Actor {
    val fsm: ActorRef = context.actorOf(Props[ItemFSM])
    var erpData: Option[ERPData] = None
    var specData: Option[SpecData] = None
    var prodData: Option[Queue[_]] = None

    implicit val formats = Serialization.formats(NoTypeHints)

    def receive = {
        case (x: ProdEvent, y: ProdData) => fsm ! (x, y)
        case x: ERPData => erpData = Some(x)
        case x: SpecData => {
            specData = Some(x)
            trySubmit()
        }
        case x: Queue[_] => prodData = Some(x)
    }

    def itemData: ItemData = {
        val item = for {
            e <- erpData
            s <- specData
            p <- prodData
        } yield ItemData(e, s, p)
        item.get
    }

    def serialize(item: ItemData): String = {
        write(item)
    }

    def trySubmit() {
        erpData.isDefined && specData.isDefined && prodData.isDefined match {
            case true => context.parent ! serialize(itemData)
            case _ => ()
        }
    }
} 
开发者ID:jlagarden,项目名称:dhbw-project-app,代码行数:54,代码来源:Item.scala

示例15: unjsonify

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

import org.json4s.JsonAST.JValue
import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods._
import org.json4s.native.Serialization
import org.json4s.native.Serialization._


  def unjsonify[T : Manifest](json: String): T = {
    unjsonify(parse(json))
  }

  def unjsonify[T : Manifest](json: JValue): T = {
    implicit val formats = Serialization.formats(NoTypeHints)
    val camelCased = json transformField {
      case (name, value) => (underscoreToCamel(name), value)
    }
    camelCased.extract[T]
  }
} 
开发者ID:rub0,项目名称:tbot,代码行数:22,代码来源:JsonUtils.scala


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