本文整理汇总了Scala中org.json4s.DefaultFormats类的典型用法代码示例。如果您正苦于以下问题:Scala DefaultFormats类的具体用法?Scala DefaultFormats怎么用?Scala DefaultFormats使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DefaultFormats类的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: SimpleKafkaProducer
//设置package包名称以及导入依赖的类
package com.example
import java.util.Properties
import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}
import org.json4s.{DefaultFormats, jackson}
class SimpleKafkaProducer(kafkaSocket: Socket, topic: String, brokers: Int = 1) {
private val serializer = "org.apache.kafka.common.serialization.StringSerializer"
private def configuration = {
val props = new Properties()
props.put("bootstrap.servers", kafkaSocket.toString())
props.put("key.serializer", serializer)
props.put("value.serializer", serializer)
props
}
def send[T <: AnyRef](message: T) = {
implicit val serialization = jackson.Serialization
implicit val formats = DefaultFormats
val producer = new KafkaProducer[String, String](configuration)
val jsonMessage = serialization.write[T](message)
val data = new ProducerRecord[String, String](topic, jsonMessage)
producer.send(data)
producer.close()
}
}
示例3: ItemController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import com.github.tototoshi.play2.json4s.native.Json4s
import models.{Item, ItemDetail}
import org.json4s.{DefaultFormats, Extraction}
import parsers.ItemParser
import play.api.mvc.{Action, Controller}
import requests.UploadZipItemForm
import scalikejdbc.DB
class ItemController @Inject()(json4s: Json4s) extends Controller {
import json4s._
import Responses._
import models.PersistItem.getItemId
implicit val formats = DefaultFormats
def list() = Action {
import models.Aliases.i
val items = Item.findAll(i.name :: Nil)
Ok(Extraction.decompose(items))
}
def show(itemId: Long) = Action {
Item.findById(itemId).fold(notFound(s"itemId = ${itemId}")) { item =>
Ok(Extraction.decompose(item))
}
}
def upload() = Action(parse.multipartFormData){ implicit req =>
UploadZipItemForm.fromReq(req).fold(BadRequest("Form error")){ form =>
DB localTx { implicit session =>
ZipUtil.inputStreams(form.file.ref.file).foreach{ is =>
ItemParser.parse(is).foreach{ item =>
val itemId = getItemId(item.name)
ItemDetail.deleteById(itemId)
ItemDetail.create(item.detail(itemId))
}
}
}
Redirect(routes.MyAssets.at("uploader.html"))
}
}
}
示例4: TwitterService
//设置package包名称以及导入依赖的类
package com.inspiringsolutions.tweet.services
import javax.inject.{Inject, Singleton}
import akka.actor.{ActorRef, ActorSystem}
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Sink
import com.inspiringsolutions.tweet.actors.CompleteStream
import com.inspiringsolutions.tweet.models.{LimitNotice, Tweet}
import org.json4s.DefaultFormats
import org.json4s.native.JsonMethods._
import org.slf4j.LoggerFactory
import play.api.Play
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success, Try}
@Singleton
class TwitterService @Inject() (twitterStreamService: TwitterStreamProducerService) {
private val log = LoggerFactory.getLogger(getClass)
implicit lazy val actorSystem: ActorSystem = Play.unsafeApplication.injector.instanceOf[ActorSystem]
implicit val materializer = ActorMaterializer()
implicit val formats = DefaultFormats
def processStreamToActorRef(streamConsumerRef: ActorRef, hashTag: String) {
val streamFuture = twitterStreamService.produceStream(hashTag)
streamFuture.onComplete {
case Failure(ex) => log.error("Error while processing stream", ex)
case Success(stream) =>
stream.scan("")((acc, curr) => {
if (acc.contains("\r\n"))
curr.utf8String
else
acc + curr.utf8String
})
.filter(_.contains("\r\n")).filterNot(_.trim.isEmpty)
.map { tryParse }
.runWith(Sink.actorRef(streamConsumerRef, CompleteStream))
}
}
private def tryParse(json: String) = {
val parsed = parse(json)
val tweetAttempt = Try(parsed.extract[Tweet])
if (tweetAttempt.isSuccess) {
tweetAttempt
} else {
Try(parsed.extract[LimitNotice])
}
}
}
示例5: DataConsumer
//设置package包名称以及导入依赖的类
package com.ruimorais
import akka.http.scaladsl.server.Directives._
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.json4s.jackson.Serialization.writePretty
import org.json4s.{DefaultFormats, jackson}
import scala.concurrent.Future
object DataConsumer extends Json4sSupport {
implicit val serialization = jackson.Serialization // or native.Serialization
implicit val formats = DefaultFormats
val route =
path("data") {
post {
entity(as[RootObject]) {
data =>
println(writePretty(data))
complete(Future.successful(data.toString))
}
}
}
}
示例6: TweetReader
//设置package包名称以及导入依赖的类
package classes
import org.json4s._
import org.json4s.native.JsonMethods._
import org.json4s.DefaultFormats
object TweetReader {
implicit val format = new DefaultFormats {
}
def getTweets(json: String): List[Tweet] = parse(json).extract[List[Tweet]]
def toTweetSet(l: List[Tweet]): TweetSet = l.foldLeft(new Empty: TweetSet)(_.incl(_))
def unparseToData(tws: List[Tweet]): String = {
val buf = new StringBuilder
for (tw <- tws) {
val json = "{ \"user\": \"" + tw.user + "\", \"text\": \"" +
tw.text.replaceAll( """"""", "\\\\\\\"") + "\", \"retweets\": " +
tw.retweets + ".0 }"
buf.append(json + ",\n")
}
buf.toString()
}
val sites = List("gizmodo", "TechCrunch", "engadget", "amazondeals", "CNET", "gadgetlab", "mashable")
private val gizmodoTweets = getTweets(TweetData.gizmodo)
private val techCrunchTweets = getTweets(TweetData.TechCrunch)
private val engadgetTweets = getTweets(TweetData.engadget)
private val amazondealsTweets = getTweets(TweetData.amazondeals)
private val cnetTweets = getTweets(TweetData.CNET)
private val gadgetlabTweets = getTweets(TweetData.gadgetlab)
private val mashableTweets = getTweets(TweetData.mashable)
private val sources = List(gizmodoTweets, techCrunchTweets, engadgetTweets, amazondealsTweets, cnetTweets, gadgetlabTweets, mashableTweets)
val tweetMap: Map[String, List[Tweet]] =
Map() ++ Seq(sites(0) -> gizmodoTweets,
sites(1) -> techCrunchTweets,
sites(2) -> engadgetTweets,
sites(3) -> amazondealsTweets,
sites(4) -> cnetTweets,
sites(5) -> gadgetlabTweets,
sites(6) -> mashableTweets)
val tweetSets: List[TweetSet] = sources.map(toTweetSet)
private val siteTweetSetMap: Map[String, TweetSet] =
Map() ++ (sites zip tweetSets)
private def unionOfAllTweetSets(curSets: List[TweetSet], acc: TweetSet): TweetSet =
if (curSets.isEmpty) acc
else unionOfAllTweetSets(curSets.tail, acc.union(curSets.head))
val allTweets: TweetSet = unionOfAllTweetSets(tweetSets, new Empty)
}
示例7: 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)
}
))
}
示例8: JsoupTest
//设置package包名称以及导入依赖的类
package org.dele.misc.scraping
import jdk.nashorn.internal.parser.JSONParser
import org.json4s.DefaultFormats
import org.jsoup._
import collection.JavaConverters._
import org.json4s.jackson.JsonMethods._
object JsoupTest extends App {
val ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"
val searchTerm = "whitebacked planthopper"
val searchUrl = "https://www.google.com/search?site=imghp&tbm=isch&source=hp&biw=1920&bih=955&q=" + searchTerm.replace(" ", "+") + "&gws_rd=cr";
val doc = Jsoup.connect(searchUrl)
.userAgent(ua)
.referrer("https://www.google.com/").get()
implicit val fmt = DefaultFormats
doc.select("div.rg_meta").asScala.foreach{ elem =>
val src = elem.text()
val json = parse(src)
val url = (json \ "ou")
if (url != null) {
val out = url.extract[String]
println(out)
}
}
println("end")
}
示例9: SimpleKafkaConsumer
//设置package包名称以及导入依赖的类
package com.example
import java.nio.charset.StandardCharsets
import java.util.Properties
import kafka.consumer.ConsumerConfig
import org.json4s.{DefaultFormats, jackson}
import scala.collection.immutable.HashMap
class SimpleKafkaConsumer(kafkaSocket: Socket, zooKeeperSocket: Socket, groupId: String, topic: String) {
private def configuration = {
val deserializer = "org.apache.kafka.common.serialization.StringDeserializer"
val props = new Properties()
props.put("bootstrap.servers", kafkaSocket.toString())
props.put("key.deserializer", deserializer)
props.put("value.deserializer", deserializer)
props.put("group.id", groupId)
props.put("consumer.id", "consumer0")
props.put("consumer.timeout", "-1")
props.put("auto.offset.reset", "smallest")
props.put("zookeeper.sync.time.ms", "200")
props.put("zookeeper.session.timeout.ms", "6000")
props.put("zookeeper.connect", zooKeeperSocket.toString())
props.put("num.consumer.fetchers", "2")
props.put("rebalance.max.retries", "4")
props.put("auto.commit.interval.ms", "1000")
props
}
private val consumer = kafka.consumer.Consumer.create(new ConsumerConfig(configuration))
def read[T <: AnyRef]()(implicit m: Manifest[T]): Iterable[T] = {
implicit val serialization = jackson.Serialization
implicit val formats = DefaultFormats
val topicCountMap = HashMap(topic -> 1)
val consumerMap = consumer.createMessageStreams(topicCountMap)
val stream = consumerMap.get(topic).get(0)
val iterator = stream.iterator()
iterator.map(x => serialization.read[T](new String(x.message(), StandardCharsets.UTF_8))).toStream
}
def shutdown() = {
consumer.shutdown()
}
}
示例10: save
//设置package包名称以及导入依赖的类
package service
import model.IDTrait
import com.sksamuel.elastic4s.ElasticDsl.index
import com.sksamuel.elastic4s.source.JsonDocumentSource
import org.json4s.jackson.Serialization._
import org.json4s.{DefaultFormats, Formats, FieldSerializer}
import com.sksamuel.elastic4s.{ElasticClient}
import com.sksamuel.elastic4s.ElasticDsl._
import org.json4s.FieldSerializer.renameTo
import org.elasticsearch.common.settings.ImmutableSettings
def save[T <: IDTrait[E]: Manifest, E](record: T, indexName: String, indexType: String): Unit = {
val rename = FieldSerializer[T](renameTo("_id", s"${indexType}_id"))
implicit val format: Formats = DefaultFormats + rename ++ org.json4s.ext.JodaTimeSerializers.all
val _id = record._id
val jsonString = write(record)
client.execute {
index into indexName -> indexType doc JsonDocumentSource(jsonString) id _id
}
}
def close = {
client.close()
}
}
示例11: 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)
}
}
}
示例12: 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\":\"[-]\"}]"
}
}
}
示例13: 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
}
}
}
}
示例14: Of
//设置package包名称以及导入依赖的类
package com.zhranklin.notice.script
import org.json4s.{DefaultFormats, ShortTypeHints, TypeHints}
trait MessageJsonFormats {
implicit val format = new DefaultFormats {
override val typeHintFieldName = "type"
override val typeHints: TypeHints = ShortTypeHints(List(
classOf[listsources],
classOf[err],
classOf[succ],
classOf[getnews],
classOf[fetch_test],
classOf[getpictures],
classOf[create_source],
classOf[fetchnews]
))
}
}
示例15: Person
//设置package包名称以及导入依赖的类
package com.sfxcode.nosql.mongo.model
import java.text.SimpleDateFormat
import java.util.Date
import org.json4s.DefaultFormats
import org.json4s.native.Serialization._
import org.mongodb.scala.bson.ObjectId
import scala.io.Source
case class Person(
id: Long,
guid: String,
isActive: Boolean,
balance: Double,
picture: String,
age: Int,
name: String,
gender: String,
email: String,
phone: String,
address: String,
about: String,
registered: Date,
tags: List[String],
friends: List[Friend],
greeting: String,
favoriteFruit: String,
_id: ObjectId = new ObjectId()
)
case class Friend(id: Long, name: String)
object Person {
implicit val formats = new DefaultFormats {
override def dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
}
val personList: List[Person] = read[List[Person]](fromJson("/test_data.json"))
def fromJson(name: String): String = {
val is = getClass.getResourceAsStream(name)
Source.fromInputStream(is, "UTF-8").getLines().mkString
}
}