本文整理汇总了Scala中org.json4s.Formats类的典型用法代码示例。如果您正苦于以下问题:Scala Formats类的具体用法?Scala Formats怎么用?Scala Formats使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Formats类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: FibonacciREST
//设置package包名称以及导入依赖的类
package com.doanduyhai.rest
import com.doanduyhai.service.FibonacciService
import org.json4s.{DefaultFormats, Formats}
import org.scalatra.{InternalServerError, BadRequest, ScalatraServlet}
import org.scalatra.json.JacksonJsonSupport
class FibonacciREST extends ScalatraServlet with JacksonJsonSupport {
protected implicit val jsonFormats: Formats = DefaultFormats
before() {
contentType = formats("json")
}
get("/:rank") {
val rank = params("rank").toInt
try {
FibonacciService.computeFibonacci(rank)
} catch {
case ex: IllegalArgumentException => BadRequest(ex.getMessage)
case throwable: Throwable => InternalServerError(throwable.getMessage)
}
}
notFound {
contentType = "text/html"
serveStaticResource() getOrElse resourceNotFound()
}
}
开发者ID:doanduyhai,项目名称:FibonacciScalaDemo,代码行数:32,代码来源:FibonacciREST.scala
示例2: JsonExtraction
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.utils.json
import java.net.{URI, URL}
import org.json4s.JsonAST.JString
import org.json4s.jackson.JsonMethods.parse
import org.json4s.{CustomSerializer, DefaultFormats, Formats, JNull}
object JsonExtraction {
val formats = DefaultFormats + json4sDateTimeSerializer + json4sLocalDateSerializer + UriSerializer + UrlSerializer + Json4sIntToBigDecimalSerializer
def apply[A](body: String)(implicit m: Manifest[A], formats: Formats = formats): A = extractResponse[A](body)
private def extractResponse[A](body: String)(implicit m: Manifest[A], format: Formats = formats): A = Option(body) match {
case Some(b) if b.length > 0 =>
try {
parse(b, useBigDecimalForDouble = true).extract
} catch {
case t: Throwable =>
throw t
}
case _ => throw new IllegalArgumentException("A string value is required for transformation")
}
case object UriSerializer extends CustomSerializer[URI](format => ( {
case JString(uri) => URI.create(uri)
case JNull => null
}, {
case uri: URI => JString(uri.toString)
}
))
case object UrlSerializer extends CustomSerializer[URL](format => ( {
case JString(url) => new URL(url)
case JNull => null
}, {
case url: URL => JString(url.toString)
}
))
}
开发者ID:danewatts,项目名称:zap-automation,代码行数:43,代码来源:JsonExtraction.scala
示例3: 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
示例4: 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
示例5: 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
示例6: Address
//设置package包名称以及导入依赖的类
package collections
import java.util.UUID
import collections.UserStatus.UserStatus
import com.google.inject.{Inject, Singleton}
import mongo.{BaseMongoCollection, MongoDAO, MongoDBObjectId}
import org.bson.types.ObjectId
import org.joda.time.DateTime
import org.json4s.Formats
import org.json4s.ext.EnumNameSerializer
case class Address(address: String, country: String = "HK")
object UserStatus extends Enumeration {
type UserStatus = Value
val Active, Disabled = Value
}
case class TestUser(
_id: Option[ObjectId] = None, // mongodb will auto-generate the _id by default
name: String, // required
nickName: Option[String] = None, // if application-wise is optional => should use option Type and default value = None
address: Address = Address(address = "address"), // can nested object
friends: List[TestUser] = List(),
uuid: UUID = UUID.randomUUID(),
jodaDateTime: DateTime = new DateTime(),
status: UserStatus = UserStatus.Active
) extends MongoDBObjectId
@Singleton
class TestCollection @Inject() (mongoDAO: MongoDAO)
extends BaseMongoCollection[TestUser](collectionName = "test", mongoDAO) {
// add enum serializer
override protected implicit val formats: Formats = standardMongoSerializer ++ jodaTimeSerializers + new EnumNameSerializer(UserStatus)
}
开发者ID:gaplo917,项目名称:play-scala-casbah-json4s-seed,代码行数:39,代码来源:TestCollection.scala
示例7: LocaleCountrySerializer
//设置package包名称以及导入依赖的类
package com.wix.pay.stripe
import java.util.Locale
import org.json4s.JsonAST.JString
import org.json4s.reflect.TypeInfo
import org.json4s.{Formats, JsonDSL, MappingException, Serializer, _}
class LocaleCountrySerializer extends Serializer[Locale] {
private val LocaleClass = classOf[Locale]
def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), Locale] = {
case (TypeInfo(LocaleClass, _), json) => json match {
case JString(country) =>
new Locale("", country)
case x => throw new MappingException("Can't convert " + x + " to LocaleClass")
}
}
def serialize(implicit formats: Formats): PartialFunction[Any, JValue] = {
case x: Locale =>
import JsonDSL._
x.getCountry
}
}
开发者ID:wix,项目名称:libpay-stripe,代码行数:27,代码来源:LocaleCountrySerializer.scala
示例8: Connect4API
//设置package包名称以及导入依赖的类
package com.ntsdev.connect4.web
import com.ntsdev.connect4.game.Game
import com.ntsdev.connect4.model.{Cell, Board}
import com.ntsdev.connect4.wire.OptionCellSerializer
import org.json4s.{DefaultFormats, Formats}
import org.scalatra._
import org.scalatra.json._
import scala.concurrent.ExecutionContext
class Connect4API extends ScalatraServlet with JacksonJsonSupport with FutureSupport {
protected implicit lazy val jsonFormats: Formats = DefaultFormats + new OptionCellSerializer
override val executor: ExecutionContext = ExecutionContext.global
get("/startGame"){
val advanced = params("advanced")
val useAdvancedPlayer = advanced eq "true"
contentType = formats("json")
val game = new Game(Board, advanced = useAdvancedPlayer)
game.grid.board
}
post("/makeMove"){
val grid = parsedBody.extract[List[Option[Cell]]]
val game = new Game(new Board(grid))
val column = params("column").toInt
val newGame = game.makeMove(column)
if(!"".equals(newGame.winningPlayer)){
val winningPlayer = newGame.winningPlayer
Ok(newGame.grid.board, Map("Winning-Player" -> winningPlayer))
}
else {
Ok(newGame.grid.board)
}
}
}
开发者ID:neilshannon,项目名称:connect4,代码行数:42,代码来源:Connect4API.scala
示例9: OptionCellSerializerSpec
//设置package包名称以及导入依赖的类
package com.ntsdev.connect4.wire
import com.ntsdev.connect4.model.{BlackCell, RedCell}
import org.json4s.{DefaultFormats, Formats}
import org.specs2.mutable.Specification
class OptionCellSerializerSpec extends Specification {
private implicit lazy val jsonFormats: Formats = DefaultFormats + new OptionCellSerializer
private val serialization = org.json4s.jackson.Serialization
"the option cell serializer" should {
"serialize an Option[Cell]" in {
val redCell = RedCell
val listOfOptionCell = List(Some(redCell))
val redJson = serialization.write(listOfOptionCell)
redJson shouldEqual "[{\"cell\":\"[R]\"}]"
val blackCell = BlackCell
val listOfBlackOptionCell = List(Some(blackCell))
val blackJson = serialization.write(listOfBlackOptionCell)
blackJson shouldEqual "[{\"cell\":\"[B]\"}]"
val listOfBlankOptionCell = List(None)
val blankJson = serialization.write(listOfBlankOptionCell)
blankJson shouldEqual "[{\"cell\":\"[-]\"}]"
}
}
}
开发者ID:neilshannon,项目名称:connect4,代码行数:31,代码来源:OptionCellSerializerSpec.scala
示例10: Connect4APISpec
//设置package包名称以及导入依赖的类
package com.ntsdev.connect4.web
import org.json4s.{DefaultFormats, Formats}
import org.scalatra.test.specs2.MutableScalatraSpec
class Connect4APISpec extends MutableScalatraSpec {
protected implicit lazy val jsonFormats: Formats = DefaultFormats
addServlet(classOf[Connect4API], "/*")
"GET /startGame" should {
"begin a game and return the board" in {
get("/startGame?advanced=true") {
status must_== 200
}
}
"make a move" in {
val postBody =
"""
|[{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},
|{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},
|{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},
|{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},
|{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},
|{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"}]
""".stripMargin
post("/makeMove?column=0", postBody, Map("Content-Type" -> "application/json")){
status must_== 200
}
}
}
}
开发者ID:neilshannon,项目名称:connect4,代码行数:36,代码来源:Connect4APISpec.scala
示例11: ApiImplUnitTest
//设置package包名称以及导入依赖的类
package org.nikosoft.oanda.api.remove
import org.json4s.Formats
import org.json4s.jackson.JsonMethods._
import org.nikosoft.oanda.api.JsonSerializers
import org.nikosoft.oanda.api.`def`.AccountsApi.AccountsResponse
import org.scalatest.FunSuite
class ApiImplUnitTest extends FunSuite {
implicit val formats: Formats = JsonSerializers.formats
test("parse account json") {
val json =
"""{"account":{"id":"001-004-XXXXXXX-003","createdTime":"2017-05-30T07:11:30.656911765Z","currency":"EUR","createdByUserID":1442547,"alias":"MT4","marginRate":"0.02","hedgingEnabled":false,"lastTransactionID":"87","balance":"77.0033","openTradeCount":1,"openPositionCount":1,"pendingOrderCount":2,"pl":"-0.9954","resettablePL":"-0.9954","financing":"-0.0013","commission":"0.0000",
|"orders":[
| {"id":"85","createTime":"2017-06-15T09:08:02.732786641Z","type":"STOP_LOSS","tradeID":"82","clientTradeID":"72179822","price":"1.11000","timeInForce":"GTC","triggerCondition":"DEFAULT","state":"PENDING"},
| {"id":"87","createTime":"2017-06-15T09:13:56.368495444Z","replacesOrderID":"84","type":"TAKE_PROFIT","tradeID":"82","clientTradeID":"72179822","price":"1.11850","timeInForce":"GTC","triggerCondition":"DEFAULT","state":"PENDING"}
|],
|"positions":[
| {"instrument":"EUR_USD",
| "long":{"units":"5000","averagePrice":"1.11810","pl":"0.3444","resettablePL":"0.3444","financing":"-0.0024","tradeIDs":["82"],"unrealizedPL":"-2.4386"},
| "short":{"units":"0","pl":"-1.3398","resettablePL":"-1.3398","financing":"0.0011","unrealizedPL":"0.0000"},
| "pl":"-0.9954","resettablePL":"-0.9954","financing":"-0.0013","commission":"0.0000","unrealizedPL":"-2.4386"}],
|"trades":[{"id":"82","instrument":"EUR_USD","price":"1.11810","openTime":"2017-06-15T09:07:28.287005040Z","initialUnits":"1000","state":"OPEN","currentUnits":"1000","realizedPL":"0.0000","financing":"0.0000",
| "clientExtensions":{"id":"72179822","tag":"0"},"takeProfitOrderID":"87","stopLossOrderID":"85","unrealizedPL":"-2.4386"}],
|"unrealizedPL":"-2.4386","NAV":"74.5647","marginUsed":"20.0022","marginAvailable":"54.5625","positionValue":"1000.1076","marginCloseoutUnrealizedPL":"-2.3847","marginCloseoutNAV":"74.6186","marginCloseoutMarginUsed":"20.0000","marginCloseoutPositionValue":"1000.0000","marginCloseoutPercent":"0.13401","withdrawalLimit":"54.5625","marginCallMarginUsed":"20.0000","marginCallPercent":"0.26803"},
|"lastTransactionID":"87"}""".stripMargin
println(parse(json).children.head.extract[AccountsResponse])
}
}
开发者ID:cnnickolay,项目名称:oanda-scala-api,代码行数:35,代码来源:ApiImplUnitTest.scala
示例12: FunctionLink
//设置package包名称以及导入依赖的类
package common
import org.json4s.{ DefaultFormats, Formats, jackson, Serialization }
import org.json4s._
case class FunctionLink(order: Int, url: String, title: String)
extends Ordered[FunctionLink]
{
def compare(that: FunctionLink) = order.compare(that.order)
}
object CommonSerializer extends common.JsonSerializer {
def identifier = 0xfeca
implicit val formats = new DefaultFormats {
override val typeHintFieldName = "_t"
override val typeHints = ShortTypeHints(List(
classOf[FunctionLink],
classOf[Stat]
))
} ++ org.json4s.ext.JodaTimeSerializers.all
}
开发者ID:enpassant,项目名称:rapids,代码行数:23,代码来源:CommonSerializer.scala
示例13: DragonServletTest
//设置package包名称以及导入依赖的类
package org.blinkmob.scalatraseed
import org.junit.runner.RunWith
import org.scalatra.test.specs2.ScalatraSpec
import org.specs2.runner.JUnitRunner
import org.json4s.jackson.Serialization._
import org.json4s.DefaultFormats
import org.json4s.Formats
@RunWith(classOf[JUnitRunner])
class DragonServletTest extends ScalatraSpec {
implicit val jsonFormats: Formats = DefaultFormats
def is = s2"""
GET /dragon
gets you some sweet dragons $getDragons
"""
addServlet(new DragonServlet, "/dragon")
def getDragons = get("/dragon"){
val resp = read[List[Dragon]](response.body)
resp must contain(Dragon(1, "BLUE", "Saphira"), Dragon(2, "GREEN", "Puff"))
}
}
开发者ID:gnomff,项目名称:scalatra-sangria,代码行数:26,代码来源:DragonServletTest.scala
示例14: InterceptionController
//设置package包名称以及导入依赖的类
package com.innoq.integration
import akka.actor.{ActorRef, ActorSystem}
import org.json4s.{DefaultFormats, Formats, JValue}
import org.scalatra.json.JacksonJsonSupport
import org.scalatra.{FutureSupport, Ok, ScalatraServlet}
import org.slf4j.LoggerFactory
class InterceptionController(actorSystem: ActorSystem, interceptionHandler: ActorRef) extends ScalatraServlet with JacksonJsonSupport with FutureSupport {
protected implicit val jsonFormats: Formats = DefaultFormats
protected override def transformRequestBody(body: JValue): JValue = body.camelizeKeys
protected override def transformResponseBody(body: JValue): JValue = body.underscoreKeys
protected implicit def executor = scala.concurrent.ExecutionContext.Implicits.global
protected val log = LoggerFactory.getLogger(classOf[InterceptionController])
log.info("Starting interception controller")
before() {
contentType = formats("json")
}
get("/*") {
Ok
}
put("/") {
val interception = parsedBody.extract[Interception]
log.info(s"Setting interception: $interception")
interceptionHandler ! SetInterception(interception)
Ok
}
post("/") {
val interception = parsedBody.extract[Interception]
log.info(s"Adding interception: $interception")
interceptionHandler ! AddInterception(interception)
Ok
}
delete("/*") {
log.info(s"Deleting interceptions")
interceptionHandler ! DeleteInterceptions()
Ok
}
}
开发者ID:mputz86,项目名称:testing-with-logging,代码行数:51,代码来源:InterceptionController.scala
示例15: ApiImplUnitTest
//设置package包名称以及导入依赖的类
package org.nikosoft.oanda.api.remove
import org.json4s.Formats
import org.json4s.jackson.JsonMethods._
import org.nikosoft.oanda.api.JsonSerializers
import org.nikosoft.oanda.api.`def`.AccountsApi.AccountsResponse
import org.scalatest.FunSuite
class ApiImplUnitTest extends FunSuite {
implicit val formats: Formats = JsonSerializers.formats
test("parse account json") {
val json =
"""{"account":{"id":"001-004-1442547-003","createdTime":"2017-05-30T07:11:30.656911765Z","currency":"EUR","createdByUserID":1442547,"alias":"MT4","marginRate":"0.02","hedgingEnabled":false,"lastTransactionID":"87","balance":"77.0033","openTradeCount":1,"openPositionCount":1,"pendingOrderCount":2,"pl":"-0.9954","resettablePL":"-0.9954","financing":"-0.0013","commission":"0.0000",
|"orders":[
| {"id":"85","createTime":"2017-06-15T09:08:02.732786641Z","type":"STOP_LOSS","tradeID":"82","clientTradeID":"72179822","price":"1.11000","timeInForce":"GTC","triggerCondition":"DEFAULT","state":"PENDING"},
| {"id":"87","createTime":"2017-06-15T09:13:56.368495444Z","replacesOrderID":"84","type":"TAKE_PROFIT","tradeID":"82","clientTradeID":"72179822","price":"1.11850","timeInForce":"GTC","triggerCondition":"DEFAULT","state":"PENDING"}
|],
|"positions":[
| {"instrument":"EUR_USD",
| "long":{"units":"5000","averagePrice":"1.11810","pl":"0.3444","resettablePL":"0.3444","financing":"-0.0024","tradeIDs":["82"],"unrealizedPL":"-2.4386"},
| "short":{"units":"0","pl":"-1.3398","resettablePL":"-1.3398","financing":"0.0011","unrealizedPL":"0.0000"},
| "pl":"-0.9954","resettablePL":"-0.9954","financing":"-0.0013","commission":"0.0000","unrealizedPL":"-2.4386"}],
|"trades":[{"id":"82","instrument":"EUR_USD","price":"1.11810","openTime":"2017-06-15T09:07:28.287005040Z","initialUnits":"1000","state":"OPEN","currentUnits":"1000","realizedPL":"0.0000","financing":"0.0000",
| "clientExtensions":{"id":"72179822","tag":"0"},"takeProfitOrderID":"87","stopLossOrderID":"85","unrealizedPL":"-2.4386"}],
|"unrealizedPL":"-2.4386","NAV":"74.5647","marginUsed":"20.0022","marginAvailable":"54.5625","positionValue":"1000.1076","marginCloseoutUnrealizedPL":"-2.3847","marginCloseoutNAV":"74.6186","marginCloseoutMarginUsed":"20.0000","marginCloseoutPositionValue":"1000.0000","marginCloseoutPercent":"0.13401","withdrawalLimit":"54.5625","marginCallMarginUsed":"20.0000","marginCallPercent":"0.26803"},
|"lastTransactionID":"87"}""".stripMargin
println(parse(json).children.head.extract[AccountsResponse])
}
}
开发者ID:cnnickolay,项目名称:forex-trader,代码行数:35,代码来源:ApiImplUnitTest.scala
示例16: UpdateSerializer
//设置package包名称以及导入依赖的类
package ru.finagram.api.json
import org.json4s.JsonAST.JObject
import org.json4s.JsonDSL._
import org.json4s.{ DefaultFormats, Extraction, Formats, JValue, Serializer, TypeInfo }
import ru.finagram.api.{ CallbackQueryUpdate, MessageUpdate, Update }
import ru.finagram.!!!
object UpdateSerializer extends Serializer[Update] {
private val UpdateClass = classOf[Update]
override def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), Update] = {
case (TypeInfo(UpdateClass, _), json: JObject) =>
json.values match {
case v if v.contains("message") =>
json.extract[MessageUpdate]
case v if v.contains("callbackQuery") =>
json.extract[CallbackQueryUpdate]
case v => !!!(s"Not implemented deserialization for $v")
}
}
override def serialize(implicit format: Formats): PartialFunction[Any, JValue] = {
case u: MessageUpdate =>
("update_id" -> u.updateId) ~~ ("message" -> json(u.message))
case u: CallbackQueryUpdate =>
("update_id" -> u.updateId) ~~ ("callback_query" -> json(u.callbackQuery))
}
private def json(obj: AnyRef): JValue = {
implicit val formats = DefaultFormats
Extraction.decompose(obj).snakizeKeys
}
}
开发者ID:finagram,项目名称:finagram,代码行数:36,代码来源:UpdateSerializer.scala
示例17: MessageSerializer
//设置package包名称以及导入依赖的类
package ru.finagram.api.json
import org.json4s.JsonAST._
import org.json4s.JsonDSL._
import org.json4s.{ DefaultFormats, Extraction, Formats, JValue, Serializer, TypeInfo }
import ru.finagram.api._
import ru.finagram.!!!
object MessageSerializer extends Serializer[Message] {
private val MessageClass = classOf[Message]
override def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), Message] = {
case (TypeInfo(MessageClass, _), json: JObject) =>
json.values match {
case v if v.contains("video") =>
json.extract[VideoMessage]
case v if v.contains("voice") =>
json.extract[VoiceMessage]
case v if v.contains("photo") =>
json.extract[PhotoMessage]
case v if v.contains("location") =>
json.extract[LocationMessage]
case v if v.contains("document") =>
json.extract[DocumentMessage]
case v if v.contains("sticker") =>
json.extract[StickerMessage]
case v if v.contains("text") =>
json.extract[TextMessage]
case v => !!!(s"Not implement deserialization for $v")
}
}
override def serialize(implicit format: Formats): PartialFunction[Any, JValue] = {
case m: VideoMessage =>
JMessage(m) ~~ ("video" -> json(m.video))
case m: VoiceMessage =>
JMessage(m) ~~ ("voice" -> json(m.voice))
case m: PhotoMessage =>
JMessage(m) ~~ ("photo" -> json(m.photo))
case m: LocationMessage =>
JMessage(m) ~~ ("location" -> json(m.location))
case m: DocumentMessage =>
JMessage(m) ~~ ("document" -> json(m.document))
case m: StickerMessage =>
JMessage(m) ~~ ("sticker" -> json(m.sticker))
case m: TextMessage =>
JMessage(m) ~~ ("text" -> m.text)
}
private def JMessage(m: Message): JObject = {
val jobject = ("messageId" -> m.messageId) ~ ("chat" -> json(m.chat)) ~ ("date" -> m.date)
if (m.from.isEmpty) jobject else jobject ~~ ("from", json(m.from.get))
}
private def json(obj: AnyRef): JValue = {
implicit val formats = DefaultFormats
Extraction.decompose(obj)
}
}
开发者ID:finagram,项目名称:finagram,代码行数:61,代码来源:MessageSerializer.scala
示例18: Implicit
//设置package包名称以及导入依赖的类
package ru.finagram.api
import org.json4s.{ DefaultFormats, Extraction, Formats }
import org.json4s.native.JsonMethods._
package object json {
val serializers = Seq(
TelegramResponseSerializer,
UpdateSerializer,
MessageSerializer,
AnswerSerializer,
KeyboardMarkupSerializer
)
object Implicit {
implicit val formats = DefaultFormats ++ serializers
}
def compactWrite(obj: Any)(implicit formats: Formats): String = {
compact(render(Extraction.decompose(obj).snakizeKeys))
}
}
开发者ID:finagram,项目名称:finagram,代码行数:24,代码来源:package.scala
示例19: KeyboardMarkupSerializer
//设置package包名称以及导入依赖的类
package ru.finagram.api.json
import org.json4s.JsonAST.JObject
import org.json4s.{ Formats, JValue, Serializer, TypeInfo }
import ru.finagram.api.{ InlineKeyboardMarkup, KeyboardMarkup, ReplyKeyboardMarkup }
object KeyboardMarkupSerializer extends Serializer[KeyboardMarkup] {
private val KeyboardMarkupClass = classOf[KeyboardMarkup]
override def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), KeyboardMarkup] = {
case (TypeInfo(KeyboardMarkupClass, _), json: JObject) =>
json.values match {
case v if v.contains("keyboard") =>
json.extract[ReplyKeyboardMarkup]
case v if v.contains("inline_keyboard") =>
json.extract[InlineKeyboardMarkup]
}
}
override def serialize(implicit format: Formats): PartialFunction[Any, JValue] = PartialFunction.empty
}
开发者ID:finagram,项目名称:finagram,代码行数:23,代码来源:KeyboardMarkupSerializer.scala
示例20: JsonFormats
//设置package包名称以及导入依赖的类
package mandrillclient.api
import java.text.SimpleDateFormat
import mandrillclient.api.constants._
import org.json4s.ext.{JodaTimeSerializers, EnumNameSerializer}
import org.json4s.{DefaultFormats, Formats}
object JsonFormats {
val dateFormats = new DefaultFormats {
override def dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSS")
}
val formats: Formats = dateFormats ++
JodaTimeSerializers.all +
new EnumNameSerializer(ErrorName) +
new EnumNameSerializer(SendToType) +
new EnumNameSerializer(SendStatus) +
new EnumNameSerializer(MargeLanguage) +
new EnumNameSerializer(RejectReason)
}
开发者ID:btomala,项目名称:mandrill-akka-client,代码行数:21,代码来源:JsonFormats.scala
注:本文中的org.json4s.Formats类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论