本文整理汇总了Scala中org.json4s.Formats类的典型用法代码示例。如果您正苦于以下问题:Scala Formats类的具体用法?Scala Formats怎么用?Scala Formats使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Formats类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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()
}
}
示例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)
}
))
}
示例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()
}
}
示例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()
}
}
示例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))
}
}
示例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)
}
示例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
}
}
示例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)
}
}
}
示例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\":\"[-]\"}]"
}
}
}
示例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
}
}
}
}
示例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])
}
}
示例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
}
示例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"))
}
}
示例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
}
}
示例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])
}
}