本文整理汇总了Scala中org.json4s.jackson.Serialization类的典型用法代码示例。如果您正苦于以下问题:Scala Serialization类的具体用法?Scala Serialization怎么用?Scala Serialization使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Serialization类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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]
}
开发者ID:new2scala,项目名称:text-util,代码行数:61,代码来源:DomainLists.scala
示例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
}
}
开发者ID:UnityTech,项目名称:parquet-s3-backup,代码行数:61,代码来源:BackupMetadata.scala
示例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]))
}
}
开发者ID:xiaoJacky,项目名称:sparkLearning,代码行数:47,代码来源:JsonParser.scala
示例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)
}
开发者ID:shinharad,项目名称:scala-json-lab,代码行数:62,代码来源:Example.scala
示例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)
}
}
开发者ID:PapaCharlie,项目名称:IFTTT-Code-Challenge,代码行数:27,代码来源:Team.scala
示例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
}
}
开发者ID:coderdiaries,项目名称:yumi,代码行数:60,代码来源:HBaseWriterActivity.scala
示例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
}
}
开发者ID:coderdiaries,项目名称:yumi,代码行数:52,代码来源:HBaseReaderActivity.scala
示例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)
}
}
开发者ID:mputz86,项目名称:testing-with-logging,代码行数:47,代码来源:UserApiTesting.scala
示例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)
}
}
}
开发者ID:phil-rice,项目名称:CddCore2,代码行数:40,代码来源:Json.scala
示例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
}
开发者ID:andrewobukhov,项目名称:smart-house,代码行数:39,代码来源:ApiDecoder.scala
示例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)
}
开发者ID:crystal-project-inc,项目名称:streaming_user_segmentation,代码行数:50,代码来源:Segment.scala
示例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)
}}
}
开发者ID:seglo,项目名称:play-content-negotiation,代码行数:29,代码来源:AsyncController.scala
示例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
}
}
开发者ID:uts-cic,项目名称:athanor-server,代码行数:60,代码来源:Athanor.scala
示例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)))
}
}
开发者ID:tradecloud,项目名称:tradecloud-microservices-demo,代码行数:42,代码来源:SessionManager.scala
示例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
}
开发者ID:mratin,项目名称:kdom,代码行数:18,代码来源:JsonSerializable.scala
示例16: toJson
//设置package包名称以及导入依赖的类
package se.apogo.kdomai.client
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
}
开发者ID:mratin,项目名称:kdom-ai,代码行数:18,代码来源:JsonSerializable.scala
示例17: JsonFormat
//设置package包名称以及导入依赖的类
package gitbucket.core.api
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import org.joda.time.format._
import org.json4s._
import org.json4s.jackson.Serialization
import java.util.Date
import scala.util.Try
object JsonFormat {
case class Context(baseUrl: String)
val parserISO = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")
val jsonFormats = Serialization.formats(NoTypeHints) + new CustomSerializer[Date](format =>
(
{ case JString(s) => Try(parserISO.parseDateTime(s)).toOption.map(_.toDate).getOrElse(throw new MappingException("Can't convert " + s + " to Date")) },
{ case x: Date => JString(parserISO.print(new DateTime(x).withZone(DateTimeZone.UTC))) }
)
) + FieldSerializer[ApiUser]() +
FieldSerializer[ApiPullRequest]() +
FieldSerializer[ApiRepository]() +
FieldSerializer[ApiCommitListItem.Parent]() +
FieldSerializer[ApiCommitListItem]() +
FieldSerializer[ApiCommitListItem.Commit]() +
FieldSerializer[ApiCommitStatus]() +
FieldSerializer[FieldSerializable]() +
FieldSerializer[ApiCombinedCommitStatus]() +
FieldSerializer[ApiPullRequest.Commit]() +
FieldSerializer[ApiIssue]() +
FieldSerializer[ApiComment]() +
FieldSerializer[ApiContents]() +
FieldSerializer[ApiLabel]() +
ApiBranchProtection.enforcementLevelSerializer
def apiPathSerializer(c: Context) = new CustomSerializer[ApiPath](format =>
(
{
case JString(s) if s.startsWith(c.baseUrl) => ApiPath(s.substring(c.baseUrl.length))
case JString(s) => throw new MappingException("Can't convert " + s + " to ApiPath")
},
{
case ApiPath(path) => JString(c.baseUrl + path)
}
)
)
def apply(obj: AnyRef)(implicit c: Context): String = Serialization.write(obj)(jsonFormats + apiPathSerializer(c))
}
开发者ID:piggymumu,项目名称:gitbucket,代码行数:54,代码来源:JsonFormat.scala
示例18: ExportImportResource
//设置package包名称以及导入依赖的类
package cjp.catalogue.resource
import cjp.catalogue.model.PersistedCatalogueProduct
import cjp.catalogue.service._
import cjp.catalogue.utils.Logging
import org.json4s.FieldSerializer
import org.json4s.FieldSerializer.ignore
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization.write
import play.api.http.MimeTypes
import play.api.mvc.{Action, Controller}
class ExportImportResource(exportImportService: ExportImportService, catalogueImportValidator: CatalogueImportValidator) extends Controller with Logging {
val productSerializer = FieldSerializer[PersistedCatalogueProduct](
ignore("_id") orElse ignore("name") orElse ignore("version") orElse ignore("created") orElse ignore("lastModified")
)
implicit val formats = CjpFormats.formats + productSerializer
def export = Action {
Ok(write(exportImportService.export)).as(MimeTypes.JSON)
}
def importCatalogue = Action(parse.tolerantText(parse.UNLIMITED)) {
implicit request =>
try {
val catalogueExport: CatalogueData = Serialization.read[CatalogueData](request.body)
val importValidation = catalogueImportValidator.validate(catalogueExport)
if (importValidation.isValid) {
exportImportService.importCatalogue(catalogueExport)
NoContent
} else {
BadRequest(write(importValidation))
}
} catch {
case e => {
error("error importing catalogue", e)
InternalServerError(e.getMessage)
}
}
}
}
开发者ID:UKHomeOffice,项目名称:product-catalogue,代码行数:46,代码来源:ExportImportResource.scala
示例19: toJsonString
//设置package包名称以及导入依赖的类
package com.groupon.dse.schema
import com.groupon.dse.commons.SchemaPrettyPrinter
import com.groupon.dse.commons.Utils._
import org.json4s.jackson.Serialization
import scala.collection.immutable.HashMap
def toJsonString: String = {
try{
Serialization.write(content)
}catch {
case e: Exception =>
throw SchemaSerializationException(e.getMessage)
}
}
}
case class SchemaSerializationException(message: String) extends Exception(message)
开发者ID:groupon,项目名称:schema-inferer,代码行数:20,代码来源:Schema.scala
示例20: HelloLambda
//设置package包名称以及导入依赖的类
package com.virtuslab.lambda.hello
import java.io.{InputStream, OutputStream, OutputStreamWriter}
import com.amazonaws.services.lambda.runtime.{Context, RequestStreamHandler}
import com.virtuslab.lambda.hello.HelloLambda.formats
import org.json4s.NoTypeHints
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization._
object HelloLambda {
implicit val formats = Serialization.formats(NoTypeHints)
}
class HelloLambda extends RequestStreamHandler {
override def handleRequest(input: InputStream, output: OutputStream, context: Context): Unit = {
context.getLogger.log(s"Log: ${context.getRemainingTimeInMillis}")
println(s"Test ${context.getAwsRequestId}")
try {
val writer = new OutputStreamWriter(output, "UTF-8")
writer.write(write(s"Fetched with ID: ${context.getAwsRequestId}"))
writer.flush()
writer.close()
} catch {
case e: Throwable => context.getLogger.log(s"exception? -> ${e.getCause}")
}
}
}
开发者ID:pdolega,项目名称:lambda-samples,代码行数:31,代码来源:HelloLambda.scala
注:本文中的org.json4s.jackson.Serialization类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论