本文整理汇总了Scala中org.json4s.jackson.Serialization类的典型用法代码示例。如果您正苦于以下问题:Scala Serialization类的具体用法?Scala Serialization怎么用?Scala Serialization使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Serialization类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: DomainLists
//设置package包名称以及导入依赖的类
package org.dele.text.lapa.patterns
import org.dele.text.lapa.ErrorHandling.{DomainListDefsErrorDomainNotFound}
import DomainStructure.{LangDomainManager, Domain}
import TLangPattern.LangPatternDomain
import org.dele.text.maen.{AtomPropMatcherLib, ConfValueStringParser, TAtomMatcher}
import org.dele.text.maen.matchers.{SubMatchCheckerLib, TMatcher}
import org.json4s.NoTypeHints
import org.json4s.jackson.JsonMethods._
import org.json4s.jackson.Serialization
object DomainLists {
import TMatcher._
import DomainStructure.genId
//private def parseEntry(entry:String, matcherGen:TMatcherGen):TAtomMatcher = {
//val (tmplId, tmplParams) = ConfValueStringParser.parse(entry)
//AtomPropMatcherLib.spawn(tmplId, tmplParams)
//matcherGen.spawn(entry, )
//}
sealed class ListDef(val id:String, val lines:List[List[String]]) {
def getMatcher(domain:Domain, matcherGen:TMatcherGen, regexDict:Map[String,String])(implicit domainManager:LangDomainManager, subMatchCheckerLib: SubMatchCheckerLib):TMatcher = {
val mid = genId(domain.id, id)
implicit val domainId = Option(domain.id)
if (lines.size == 1) ListNGram(lines.head.map(e => {
val parsed = ConfValueStringParser.parse(e)
matcherGen.spawn(parsed, None, regexDict).get
}), Option(mid))
else matchersOR(mid, lines.map(
l => {
ListNGram(l.map(e => {
val parsed = ConfValueStringParser.parse(e)
matcherGen.spawn(parsed, None, regexDict).get
}))
}
))
}
}
sealed class DomainListDefs(val domain:String, val lists:List[ListDef]) {
private val _map:Map[String,ListDef] = lists.map(l => (l.id, l)).toMap
def getMatchers(matcherGen:TMatcherGen, regexDict:Map[String,String])(implicit domainManager:LangDomainManager, subMatchCheckerLib: SubMatchCheckerLib):Set[TMatcher] = {
val d = domainManager.getDomain(domain)
if (d.isEmpty) throw DomainListDefsErrorDomainNotFound(domain)
else lists.map(_.getMatcher(d.get, matcherGen, regexDict)).toSet
}
}
sealed class LangDomainLists(val lang:String, val domainLists:List[DomainListDefs]) {
private val _map:Map[String,DomainListDefs] = domainLists.map(dl => (dl.domain, dl)).toMap
def getMatchers(matcherGen:TMatcherGen, regexDict:Map[String,String])(implicit domainManager:LangDomainManager, subMatchCheckerLib: SubMatchCheckerLib):Set[TMatcher] =
domainLists.map(_.getMatchers(matcherGen, regexDict)).foldLeft(Set[TMatcher]())(_ ++ _)
}
implicit val _formats = Serialization.formats(NoTypeHints)
def loadDomainLists(json:String):LangDomainLists = parse(json).extract[LangDomainLists]
}
示例2: BackupMetadata
//设置package包名称以及导入依赖的类
package com.unity.analytics.spark.utils.parquet
import java.sql.DriverManager
import org.apache.spark.Logging
import org.json4s.jackson.Serialization
case class BackupMetadata(
backupId: String,
backupEntries: Array[BackupEntry]
)
case class BackupEntry(
srcDir: String,
destDir: String,
srcNumFiles: Int = 1,
destNumFiles: Int = 1
)
object BackupMetadata extends Logging {
val tableName = "backup_metadata"
implicit val formats = org.json4s.DefaultFormats
def write(backupId: String, backupEntries: Array[BackupEntry], jdbcConfig: Map[String, String]): Unit = {
val connection = DriverManager.getConnection(jdbcConfig.get("url").get)
val backupEntriesJSON = Serialization.write[Array[BackupEntry]](backupEntries)
val sql = s"""INSERT INTO ${BackupMetadata.tableName} (id, entries) VALUES ('$backupId', '$backupEntriesJSON') ON DUPLICATE KEY UPDATE entries = '$backupEntriesJSON'"""
try {
connection.prepareStatement(sql).execute()
}
finally {
connection.close()
}
}
def read(backupId: String, jdbcConfig: Map[String, String]): Option[BackupMetadata] = {
//Read from MySQL
val connection = DriverManager.getConnection(jdbcConfig.get("url").get)
val sql = s"SELECT * FROM $tableName WHERE id = '$backupId'"
try {
val results = connection.prepareStatement(sql).executeQuery()
while (results.next()) {
val backupEntriesJSON = results.getString("entries")
val backupEntries = Serialization.read[Array[BackupEntry]](backupEntriesJSON)
return Some(BackupMetadata(backupId, backupEntries))
}
}
catch {
case e: Exception => {
logError(s"Error loading backup BackupMetadata $backupId - ${e.getMessage}")
}
}
finally {
connection.close()
}
None
}
}
示例3: Book
//设置package包名称以及导入依赖的类
package com.learn.spark.utils
import org.json4s.JsonDSL._
import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization._
case class Book(val author: String, val content: String, val id: String, val time: Long, val title: String)
case class Person(var map: Map[String, String]){
def id: String = map.getOrElse("id", "")
}
def parseBeanToString[T <: AnyRef](bean: T): String = {
implicit val formats = Serialization.formats(NoTypeHints)
write(bean)
}
def main(args: Array[String]) {
val c = List(1, 2, 3)
val d = compact(render(c))
println(d)
val json = "{\"author\":\"hll\",\"content\":\"ES?etamsports\",\"id\":\"693\",\"time\":1490165237200,\"title\":\"????\"}"
implicit val mf = manifest[Book]
val book = parseJsonToBean[Book](json)
println(book.content)
val string = parseBeanToString(book)
println(string)
val map = Map("124" -> "456", "333" -> "789")
val person = Person(map)
val personStr = parseBeanToString(person)
println(personStr)
person.map += ("124" -> "789")
println(person)
println(parseJsonToBean[Person](personStr)(manifest[Person]))
}
}
示例4: 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)
}
示例5: makePairs
//设置package包名称以及导入依赖的类
package ifttt
import ifttt.Scheduler.makeOrderedPair
lazy val pairs: Set[(String, String)] = {
def makePairs(emails: List[String]): List[(String, String)] = {
emails match {
case hd :: tl => tl.map(makeOrderedPair(hd, _)) ::: makePairs(tl)
case Nil => List()
}
}
// By sorting the pairs, we ensure that if two people are both part of two distinct teams, the pairs that contains
// their emails will be in the same order in both teams.
makePairs(members.toList).toSet
}
def toJson: String = {
import org.json4s._
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization.write
implicit val formats = Serialization.formats(NoTypeHints)
write(this)
}
}
示例6: HBaseWriterActivity
//设置package包名称以及导入依赖的类
package yumi.pipeline.activities.connectors.hbase
import org.apache.spark.sql.execution.datasources.hbase.{HBaseRelation, HBaseTableCatalog}
import org.json4s.NoTypeHints
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization.write
import yumi.pipeline.{Activity, Parameters, SessionData, YumiContext}
class HBaseWriterActivity (val parameters: Parameters) extends Activity{
val format = "org.apache.spark.sql.execution.datasources.hbase"
val mode = parameters
.getOptionAs[String]("mode")
.getOrElse("append")
val table = parameters.getAs[String]("table")
val as = parameters.getAs[String]("as")
val namespace = parameters.getAs[String]("namespace")
val rowKey = parameters.getAs[String]("rowKey")
val columns = parameters.getAs[List[Map[Any, Any]]]("columns")
val zookeeperQuorum = parameters.getAs[String]("zookeeper.quorum")
val zookeeperZnodeParent = parameters.getAs[String]("zookeeper.znode.parent")
override protected[this] def onInvoke(sessionData: SessionData)
(implicit yumiContext: YumiContext): SessionData = {
import yumiContext._
implicit val formats = Serialization.formats(NoTypeHints)
val columnString = columns.map(x=> write(x).stripPrefix("{").stripSuffix("}")).mkString(",")
val catalog = s"""{
|"table":{"namespace":"$namespace", "name":"$as"},
|"rowkey":"$rowKey",
|"columns":{$columnString}
|}""".stripMargin
val connection = s"""{
"hbase.zookeeper.quorum":"$zookeeperQuorum",
"zookeeper.znode.parent":"$zookeeperZnodeParent"
}
"""
dataFrameWriter.write(
dataFrame = sparkSession.table(table),
format = format,
mode = mode,
options = Map(HBaseTableCatalog.tableCatalog -> catalog,
HBaseRelation.HBASE_CONFIGURATION -> connection),
path = format
)
sessionData
}
}
示例7: HBaseReaderActivity
//设置package包名称以及导入依赖的类
package yumi.pipeline.activities.connectors.hbase
import org.apache.spark.sql.execution.datasources.hbase.{HBaseRelation, HBaseTableCatalog}
import org.json4s.NoTypeHints
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization.write
import yumi.pipeline.{Activity, Parameters, SessionData, YumiContext}
class HBaseReaderActivity(val parameters: Parameters) extends Activity {
val table = parameters.getString("table")
val asView = parameters.getString("as")
val namespace = parameters.getString("namespace")
val rowKey = parameters.getString("rowKey")
val columns = parameters.getAs[List[Map[Any, Any]]]("columns")
val zookeeperQuorum = parameters.getString("zookeeper.quorum")
val zookeeperZnodeParent = parameters.getString("zookeeper.znode.parent")
override protected[this] def onInvoke(sessionData: SessionData)
(implicit yumiContext: YumiContext): SessionData = {
import yumiContext._
implicit val formats = Serialization.formats(NoTypeHints)
val columnString = columns.map(x=> write(x).stripPrefix("{").stripSuffix("}")).mkString(",")
val catalog = s"""{
|"table":{"namespace":"$namespace", "name":"$table"},
|"rowkey":"$rowKey",
|"columns":{$columnString}
|}""".stripMargin
val connection = s"""{
"hbase.zookeeper.quorum":"$zookeeperQuorum",
"zookeeper.znode.parent":"$zookeeperZnodeParent"
}
"""
sparkSession
.read
.options(Map(HBaseTableCatalog.tableCatalog -> catalog,
HBaseRelation.HBASE_CONFIGURATION -> connection))
.format("org.apache.spark.sql.execution.datasources.hbase")
.load()
.createTempView(asView)
sessionData
}
}
示例8: UserApiTesting
//设置package包名称以及导入依赖的类
package com.innoq.tests.utils
import com.innoq.framework.TestingBase
import com.innoq.framework.utils.{HttpInterceptionTesting, Methods}
import org.json4s.NoTypeHints
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization._
object UserApiTesting {
implicit private val formats = Serialization.formats(NoTypeHints)
case class CreateUser(name: String, password: String)
case class User(id: String, name: String, password: String, balance: Int)
}
class UserApiTesting(test: TestingBase with HttpInterceptionTesting) {
import UserApiTesting._
private val userApiUrl = test.infrastructureConfig.getString("services.user.url")
def createUser(name: String, password: String) = {
val createUser = CreateUser(name, password)
val json = write(createUser)
val r = test.requestAndWait(s"$userApiUrl/users/", Methods.POST, json)
test.parseResponse[User](r)
}
def getUser(id: String) = {
val r = test.requestAndWait(s"$userApiUrl/users/$id", Methods.GET)
test.parseResponse[User](r)
}
def credit(userId: String, amount: Int) = {
val r = test.requestAndWait(s"$userApiUrl/users/$userId/credit/$amount", Methods.POST)
test.parseResponse[User](r)
}
def debit(userId: String, amount: Int) = {
val r = test.requestAndWait(s"$userApiUrl/users/$userId/debit/$amount", Methods.POST)
test.parseResponse[User](r)
}
}
示例9: JsonSituation
//设置package包名称以及导入依赖的类
package org.cddcore.json
import org.cddcore.structure.{PathRootAndSteps, Situation, Structure}
import org.json4s.jackson.{JsonMethods, Serialization}
import org.json4s.{DefaultFormats, JValue}
/** To use this you probably need to
import JsonSituation._
*/
class JsonSituation (implicit structure: Structure[JValue]) extends Situation[JValue] {
def parse(s: String)(implicit formats: DefaultFormats = DefaultFormats) = root(JsonMethods.parse(s))
}
object JsonSituation {
implicit object JsonStructure extends Structure[JValue] {
override def findResult(pathRootAndSteps: PathRootAndSteps[JValue]): Iterable[JValue] = {
import pathRootAndSteps._
List(steps.foldLeft(root: JValue) { case (acc, step) =>
step.linked match {
case true => acc \ step.element
case false => acc \\ step.element
}
})
}
override def structureTitle: String = "json"
override def sToString(s: JValue): String = {
implicit val formats = DefaultFormats
Serialization.writePretty(s)
}
}
}
示例10: ApiDecoder
//设置package包名称以及导入依赖的类
package smarthouse.restapi.http.ws
import org.json4s.JsonAST.JString
import org.json4s.NoTypeHints
import org.json4s.jackson.JsonMethods._
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization._
import smarthouse.restapi.http.ws.models.{ApiMessage, Heartbeat}
import scala.util.{Failure, Success, Try}
object ApiDecoder extends JsonSerializers {
implicit val formats = Serialization.formats(NoTypeHints) + memberStatusSerializer + uriSerializer + offsetDateTime
def decodeRequest(requestString: String): Option[ApiMessage] = {
Try {
parse(requestString) \ "messageType" match {
case JString("Heartbeat") => read[Heartbeat](requestString)
case _ => throw InvalidRequestException
}
} match {
case Success(x) => Some(x)
case Failure(_) => None
}
}
def encodeRequest(apiMessage: ApiMessage): String = {
write(apiMessage)
}
def encodeCustom(msg: AnyRef): String = {
write(msg)
}
case object InvalidRequestException extends RuntimeException
}
示例11: Segment
//设置package包名称以及导入依赖的类
package com.crystal
package models
// Kinesis
import stores.KinesisStream
// JSON
import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization.{read, write}
// Rules
import rule_engine.rules.Rule
case class Segment(val name: String, rule: Rule) {
import Segment._
def containsUser(user: User): Boolean = {
rule.fulfilledBy(user.toMap)
}
def alreadyContainedUser(user: User): Boolean = {
val userWithoutNewEvents = User(user.id, user.persistedActions)
rule.fulfilledBy(userWithoutNewEvents.toMap)
}
def publishUserEntrance(user: User) = {
implicit val formats = Serialization.formats(ShortTypeHints(List(classOf[EnterSegmentEvent])))
val event = EnterSegmentEvent(user.id, name)
stream.put(user.id, write(event).getBytes("UTF-8"))
}
def publishUserExit(user: User) = {
implicit val formats = Serialization.formats(ShortTypeHints(List(classOf[ExitSegmentEvent])))
val event = ExitSegmentEvent(user.id, name)
stream.put(user.id, write(event).getBytes("UTF-8"))
}
}
object Segment {
val config = AppConfig.load().get
val stream = KinesisStream(config.outStreamName)
case class EnterSegmentEvent(user_id: String, segment_name: String)
case class ExitSegmentEvent(user_id: String, segment_name: String)
}
示例12: AsyncController
//设置package包名称以及导入依赖的类
package controllers
import java.util.Date
import javax.inject._
import akka.actor.ActorSystem
import models._
import org.json4s._
import org.json4s.jackson.Serialization
import play.api.mvc._
import scala.concurrent.{ExecutionContext, Future}
@Singleton
class AsyncController @Inject() (actorSystem: ActorSystem)(implicit exec: ExecutionContext)
extends Controller with ContentNegotiation {
implicit val formats = Serialization.formats(NoTypeHints)
def project = negotiateAction { implicit request => Future {
val project = Project("test", new Date, Some(Language("Scala", 2.75)), List(
Team("QA", List(Employee("John Doe", 5), Employee("Mike", 3))),
Team("Impl", List(Employee("Mark", 4), Employee("Mary", 5), Employee("Nick Noob", 1)))))
Content(project)
}}
}
示例13: Athanor
//设置package包名称以及导入依赖的类
package au.edu.utscic.athanorserver.athanor
import au.edu.utscic.athanorserver.data.RhetoricalImplicits
import au.edu.utscic.athanorserver.data.RhetoricalTypes._
import com.typesafe.config.{Config, ConfigFactory}
import com.xerox.jatanor.JAtanor
import org.json4s.JsonAST.JValue
import org.json4s.NoTypeHints
import org.json4s.jackson.JsonMethods.parse
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization.write
import scala.io.Source
object Athanor {
lazy val config: Config = ConfigFactory.load()
lazy val path: String = config.getString("app.path")
lazy val athanor = new JAtanor
lazy val handler = athanor.LoadProgram(program,"")
lazy val program: String = fullPath("apply.kif")
lazy val testSentence: String = fullPath("sentence.json")
lazy val demoFile:String = Source.fromFile(testSentence).getLines.mkString
def fullPath(file:String): String = {
s"$path/scripts/$file"
}
def parseJsonSentence(sent:String):ParsedSentence = {
import RhetoricalImplicits._
val json:JValue = parse(sent)
val lexNodes:LexicalNodes = json(0)
val constTree:ConstituentTree = json(1).extract[ConstituentTree]
val deps:Dependencies = json(2).extract[Dependencies]
(lexNodes,constTree,deps)
}
def parsedSentenceToJsonString(parsedSent:ParsedSentence):String = {
implicit val formats = Serialization.formats(NoTypeHints)
val l = write(parsedSent._1)
val c = write(parsedSent._2).replaceAll("""(\"(?=[0-9]))|((?<=[0-9])\")""","") //remove quotes around Ints for json
val d = write(parsedSent._3)
s"[$l,$c,$d]"
}
def analyseParsedSentence(parsed:ParsedSentence):List[String] = {
val jsonStr:String = parsedSentenceToJsonString(parsed)
this.analyseJson(jsonStr)
}
def analyseJson(json:String):List[String] = {
athanor.ExecuteFunctionArray(handler,"Apply",List(json).toArray).toList
}
}
示例14: SessionManager
//设置package包名称以及导入依赖的类
package nl.tradecloud.common.utils.session
import com.typesafe.config.Config
import net.ceedubs.ficus.Ficus._
import net.ceedubs.ficus.readers.ArbitraryTypeReader._
import org.json4s.Formats
import org.json4s.jackson.Serialization
import pdi.jwt.algorithms.JwtHmacAlgorithm
import pdi.jwt.{Jwt, JwtAlgorithm, JwtClaim}
import scala.util.Try
class SessionManager[T <: AnyRef](config: Config)(implicit val formats: Formats, mf: Manifest[T]) {
private[this] final val sessionConfig: SessionConfig = config.as[SessionConfig]("akka.http.session")
private[this] final val algorithm: JwtHmacAlgorithm = JwtAlgorithm.HS256
lazy val setHeaderName: String = sessionConfig.setHeaderName.getOrElse("Set-Authorization")
lazy val headerName: String = sessionConfig.headerName.getOrElse("Authorization")
def encode(sessionData: T): String = {
val claim: JwtClaim = JwtClaim(
content = Serialization.write[T](sessionData)
)
Jwt.encode(
sessionConfig.headerTtl
.map(ttl => claim.issuedNow.expiresIn(ttl))
.getOrElse(claim),
sessionConfig.secret,
algorithm
)
}
def decode(token: String): Try[T] = {
Jwt.decode(
token,
sessionConfig.secret,
Seq(algorithm)
).flatMap(t => Try(Serialization.read[T](t)))
}
}
示例15: toJson
//设置package包名称以及导入依赖的类
package se.apogo.kdom.api.model
import org.json4s.NoTypeHints
import org.json4s.jackson.Serialization
trait JsonSerializable {
import org.json4s.native.JsonMethods._
implicit val formats = Serialization.formats(NoTypeHints)
def toJson: String = {
val json = Serialization.writePretty(this)
pretty(render(parse(json)))
}
}
case class JsonString(string: String) extends JsonSerializable {
override def toJson: String = string
}