本文整理汇总了Scala中org.json4s.Extraction类的典型用法代码示例。如果您正苦于以下问题:Scala Extraction类的具体用法?Scala Extraction怎么用?Scala Extraction使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Extraction类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: 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"))
}
}
}
开发者ID:ponkotuy,项目名称:FactorioRecipe,代码行数:46,代码来源:ItemController.scala
示例2: dbObj2Obj
//设置package包名称以及导入依赖的类
package mongo
import com.mongodb.DBObject
import com.mongodb.casbah.MongoCollection
import org.json4s.Extraction
import org.json4s.JsonAST.JField
import org.json4s.mongo.JObjectParser
import org.json4s.JsonDSL._
import org.json4s.mongo.JObjectParser._
trait MongoObjectHelper[A]{
protected implicit val formats: org.json4s.Formats
def dbObj2Obj[T](o: MongoCollection#T)(implicit m: Manifest[A]): A = {
val json = JObjectParser.serialize(o)
Extraction.extract[A](json)
}
def obj2DbObj(obj: A): DBObject = {
JObjectParser.parse(Extraction.decompose(obj))
}
}
开发者ID:gaplo917,项目名称:play-scala-casbah-json4s-seed,代码行数:25,代码来源:MongoObjectHelper.scala
示例3: DecompileLayoutSerializer
//设置package包名称以及导入依赖的类
package org.argus.amandroid.serialization
import org.argus.amandroid.core.decompile.DecompileLayout
import org.argus.jawa.core.util.{FileResourceUri, ISet}
import org.json4s.{CustomSerializer, Extraction, JValue}
import org.json4s.JsonDSL._
object DecompileLayoutSerializer extends CustomSerializer[DecompileLayout](format => (
{
case jv: JValue =>
implicit val formats = format
val outputUri = (jv \ "outputUri").extract[FileResourceUri]
val createFolder = (jv \ "createFolder").extract[Boolean]
val srcFolder = (jv \ "srcFolder").extract[String]
val libFolder = (jv \ "libFolder").extract[String]
val createSeparateFolderForDexes = (jv \ "createSeparateFolderForDexes").extract[Boolean]
val pkg = (jv \ "pkg").extract[String]
val outputSrcUri = (jv \ "outputSrcUri").extract[FileResourceUri]
val sourceFolders = (jv \ "sourceFolders").extract[ISet[String]]
val libFolders = (jv \ "libFolders").extract[ISet[String]]
val dependencies = (jv \ "dependencies").extract[ISet[String]]
val thirdPartyLibraries = (jv \ "thirdPartyLibraries").extract[ISet[String]]
val layout = DecompileLayout(outputUri, createFolder, srcFolder, libFolder, createSeparateFolderForDexes)
layout.pkg = pkg
layout.outputSrcUri = outputSrcUri
layout.sourceFolders = sourceFolders
layout.libFolders = libFolders
layout.dependencies = dependencies
layout.thirdPartyLibraries = thirdPartyLibraries
layout
},
{
case layout: DecompileLayout =>
implicit val formats = format
val outputUri: FileResourceUri = layout.outputSrcUri
val createFolder: Boolean = layout.createFolder
val srcFolder: String = layout.srcFolder
val libFolder: String = layout.libFolder
val createSeparateFolderForDexes: Boolean = layout.createSeparateFolderForDexes
val pkg: String = layout.pkg
val outputSrcUri: FileResourceUri = layout.outputSrcUri
val sourceFolders: ISet[String] = layout.sourceFolders
val libFolders: ISet[String] = layout.libFolders
val dependencies: ISet[String] = layout.dependencies
val thirdPartyLibraries: ISet[String] = layout.thirdPartyLibraries
("outputUri" -> outputUri) ~
("createFolder" -> createFolder) ~
("srcFolder" -> srcFolder) ~
("libFolder" -> libFolder) ~
("createSeparateFolderForDexes" -> createSeparateFolderForDexes) ~
("pkg" -> pkg) ~
("outputSrcUri" -> outputSrcUri) ~
("sourceFolders" -> Extraction.decompose(sourceFolders)) ~
("libFolders" -> Extraction.decompose(libFolders)) ~
("dependencies" -> Extraction.decompose(dependencies)) ~
("thirdPartyLibraries" -> Extraction.decompose(thirdPartyLibraries))
}
))
开发者ID:arguslab,项目名称:Argus-SAF,代码行数:60,代码来源:DecompileLayoutSerializer.scala
示例4: JSON
//设置package包名称以及导入依赖的类
package se.joham.funrts.util
import org.json4s.{CustomSerializer, Extraction, ShortTypeHints}
import se.joham.funrts.model._
import Extraction.{decompose, extract}
import org.json4s.JsonAST.JValue
import se.gigurra.scalego.serialization.KnownSubTypes
import se.gigurra.scalego.serialization.json.JsonSerializer
import se.joham.funrts.model.FunRtsECS.{ECS, IdTypes}
import org.json4s.jackson.JsonMethods.{compact, parse}
import org.json4s.jackson.JsonMethods.{pretty => prty}
object JSON {
def writeAst(ecs: ECS): JValue = ecsSerializer.SerializableOps(ecs).toJsonAst
def write(ecs: ECS, pretty: Boolean): String = ecsSerializer.SerializableOps(ecs).toJson(pretty)
def writeAst(terrain: Terrain): JValue = decompose(terrain)
def write(terrain: Terrain, pretty: Boolean): String = if (pretty) prty(writeAst(terrain)) else compact(writeAst(terrain))
def readEcsAst(ecs: ECS, json: JValue): Unit = ecsSerializer.SerializableOps(ecs).appendJsonAst(json)
def readEcs(ecs: ECS, json: String): Unit = ecsSerializer.SerializableOps(ecs).appendJson(json)
def readTerrainAst(json: JValue): Terrain = extract[Terrain](json)
def readTerrain(json: String): Terrain = readTerrainAst(parse(json))
//////////////////////////////////////////////////////////////////////////////////////
object TerrainSerializer extends CustomSerializer[Terrain](_ => ({
case json => extract[TerrainSerializable](json).toTerrain },{
case terrain: Terrain => decompose(new TerrainSerializable(terrain))
}))
case class TerrainSerializable(nx: Int, ny: Int, base64Tiles: String) {
def this(terrain: Terrain) = this(terrain.nx, terrain.ny, Base64.encodeString(terrain.tiles))
def toTerrain: Terrain = Terrain(nx, ny, Base64.decodeBinary(base64Tiles))
}
implicit lazy val jsonFormats = org.json4s.DefaultFormats + TerrainSerializer + ShortTypeHints(Action.classes)
val ecsSerializer = new JsonSerializer[IdTypes](
knownSubtypes = KnownSubTypes.fromShortClassName(types = Action.classes:_*),
jsonFormats = jsonFormats
)
}
开发者ID:GiGurra,项目名称:fun-rts,代码行数:46,代码来源:JSON.scala
示例5: Companies
//设置package包名称以及导入依赖的类
package controllers
import authes.AuthConfigImpl
import authes.Role.{Administrator, NormalUser}
import com.github.tototoshi.play2.json4s.Json4s
import com.google.inject.Inject
import jp.t2v.lab.play2.auth.AuthElement
import models.{Company, Fare, TrainType, TrainTypeSerializer}
import org.json4s.{DefaultFormats, Extraction}
import play.api.mvc.Controller
import queries.{CreateCompany, CreateFares}
import scalikejdbc._
class Companies @Inject() (json4s: Json4s) extends Controller with AuthElement with AuthConfigImpl {
import Responses._
import json4s._
implicit val formats = DefaultFormats + TrainTypeSerializer
def list() = StackAction(AuthorityKey -> Administrator) { implicit req =>
Ok(Extraction.decompose(Company.findAll(Seq(Company.defaultAlias.id))))
}
def create() = StackAction(json, AuthorityKey -> Administrator) { implicit req =>
req.body.extractOpt[CreateCompany].fold(JSONParseError) { company =>
DB localTx { implicit session =>
val id = company.company.save()
Ok(id.toString)
}
}
}
// Fare table?????????????????
def existsFare() = StackAction(AuthorityKey -> NormalUser) { implicit req =>
Ok(Extraction.decompose(Fare.existsFare()(AutoSession)))
}
def fares(companyId: Long, trainType: Int) = StackAction(AuthorityKey -> NormalUser) { implicit req =>
import models.DefaultAliases.f
TrainType.find(trainType).fold(notFound(s"train type: ${trainType}")) { tType =>
val fares = Fare.findAllBy(sqls.eq(f.companyId, companyId).and.eq(f.trainType, tType.value))
Ok(Extraction.decompose(fares))
}
}
def createFares(companyId: Long, trainType: Int) = StackAction(json, AuthorityKey -> Administrator) { implicit req =>
req.body.extractOpt[CreateFares].fold(JSONParseError) { fares =>
TrainType.find(trainType).fold(notFound(s"train type: ${trainType}")) { tType =>
DB localTx { implicit session =>
val f = Fare.column
Fare.deleteBy(sqls.eq(f.companyId, companyId).and.eq(f.trainType, trainType))
fares.fares.map(_.fare(companyId, tType)).foreach(_.save)
}
Ok("Success")
}
}
}
}
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:58,代码来源:Companies.scala
示例6: Releases
//设置package包名称以及导入依赖的类
package controllers
import authes.AuthConfigImpl
import authes.Role.Administrator
import com.github.tototoshi.play2.json4s.Json4s
import com.google.inject.Inject
import jp.t2v.lab.play2.auth.AuthElement
import models.{Diagram, TrainTypeSerializer}
import org.json4s.{DefaultFormats, Extraction}
import scalikejdbc._
import play.api.mvc.Controller
import responses.{DiagramResponse, ReleaseResponse}
class Releases @Inject() (json4s: Json4s) extends Controller with AuthElement with AuthConfigImpl {
import json4s._
implicit val format = DefaultFormats + TrainTypeSerializer
def list() = StackAction(AuthorityKey -> Administrator) { implicit req =>
import models.DefaultAliases.d
val diagrams = Diagram.joins(Diagram.stopStationRef).findAllBy(sqls.isNotNull(d.staging))
val result = diagrams.groupBy(_.staging.get).map {
case (staging, ds) =>
ReleaseResponse(staging, ds.map(DiagramResponse.fromDiagram))
}
Ok(Extraction.decompose(result))
}
}
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:29,代码来源:Releases.scala
示例7: Accounts
//设置package包名称以及导入依赖的类
package controllers
import authes.AuthConfigImpl
import authes.Role.NormalUser
import com.github.tototoshi.play2.json4s.Json4s
import com.google.inject.Inject
import jp.t2v.lab.play2.auth.AuthElement
import models.{Account, AccountSerializer, Mission}
import org.json4s.{DefaultFormats, Extraction}
import play.api.mvc.{Action, Controller}
import queries.CreateAccount
import scalikejdbc._
class Accounts @Inject() (json4s: Json4s) extends Controller with AuthElement with AuthConfigImpl {
import json4s._
import Responses._
implicit val formats = DefaultFormats + AccountSerializer
def show() = StackAction(AuthorityKey -> NormalUser) { implicit req =>
Ok(Extraction.decompose(loggedIn))
}
def showMin(id: Long) = Action {
Account.findById(id).fold(notFound("player")) { account =>
Ok(Extraction.decompose(account.minimal))
}
}
def createAccount() = Action(json) { req =>
req.body.extractOpt[CreateAccount].fold(JSONParseError) { account =>
account.account.save()(AutoSession)
Success
}
}
def missions(id: Long) = Action {
import models.DefaultAliases.m
val missions = Mission.findAllBy(sqls.eq(m.creator, id))
Ok(Extraction.decompose(missions.sortBy(-_.rate)))
}
}
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:44,代码来源:Accounts.scala
示例8: Histories
//设置package包名称以及导入依赖的类
package controllers
import authes.AuthConfigImpl
import authes.Role.Administrator
import com.github.tototoshi.play2.json4s.Json4s
import com.google.inject.Inject
import jp.t2v.lab.play2.auth.AuthElement
import models.{Diagram, History}
import org.json4s.{DefaultFormats, Extraction}
import play.api.mvc.{Action, Controller}
import queries.CreateHistory
import scalikejdbc._
class Histories @Inject() (json4s: Json4s) extends Controller with AuthElement with AuthConfigImpl {
import controllers.Responses._
import json4s._
implicit val format = DefaultFormats
def list() = Action {
import models.DefaultAliases.h
Ok(Extraction.decompose(History.findAllWithLimitOffset(limit = 20, orderings = Seq(h.id.desc))))
}
def create() = StackAction(json, AuthorityKey -> Administrator) { implicit req =>
req.body.extractOpt[CreateHistory].fold(JSONParseError) { his =>
DB.localTx { implicit session =>
his.release.foreach { r =>
Diagram.updateBy(sqls.eq(Diagram.column.staging, r)).withAttributes('staging -> None)
}
his.history().save()
Success
}
}
}
}
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:37,代码来源:Histories.scala
示例9: Validators
//设置package包名称以及导入依赖的类
package controllers
import authes.AuthConfigImpl
import authes.Role.Administrator
import com.github.tototoshi.play2.json4s.Json4s
import com.google.inject.Inject
import jp.t2v.lab.play2.auth.AuthElement
import models._
import org.json4s.{DefaultFormats, Extraction}
import play.api.mvc.Controller
import scalikejdbc.AutoSession
import utils.MethodProfiler
import validator._
class Validators @Inject() (json4s: Json4s) extends Controller with AuthElement with AuthConfigImpl {
import json4s._
implicit val format = DefaultFormats + ErrorSerializer
def list() = StackAction(AuthorityKey -> Administrator) { implicit req =>
import LineStation.{lineRef, stationRef}
val profiler = MethodProfiler.Nop
val errors = profiler("all") {
val diagrams = profiler("diagrams") {
Diagram.findAllIds()(AutoSession)
}
val stops = profiler("stops") {
StopStation.findAll()
}
val trains = profiler("trains") {
Train.allDiagramIds()(AutoSession).toSet
}
val stations = profiler("lineStations") {
LineStation.joins(lineRef, stationRef).findAll()
}
profiler("diagramsValidator") {
val validator = new DiagramValidator(stops, stations)
diagrams.flatMap(validator.validate)
} ++ profiler("stationStopValidator") {
new StationStopValidator(stops).validate(stations)
} ++ profiler("lackTrainValidator") {
val validator = new LackTrainValidator(trains)
diagrams.flatMap(validator.validate)
} ++ profiler("stationGeoValidator") {
val stations = Station.joins(Station.geoRef).findAll()
StationGeoValidator.validate(stations)
}
}
Ok(Extraction.decompose(errors))
}
}
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:52,代码来源:Validators.scala
示例10: Scraper
//设置package包名称以及导入依赖的类
package controllers
import authes.AuthConfigImpl
import authes.Role.Administrator
import com.github.tototoshi.play2.json4s.Json4s
import com.google.inject.Inject
import jp.t2v.lab.play2.auth.AuthElement
import net.liftweb.util.Html5
import org.json4s.{DefaultFormats, Extraction}
import play.api.mvc.{Action, Controller}
import scrape.model.{StationPage, TrainPage}
import scala.io.Codec
import scala.xml._
class Scraper @Inject() (json4s: Json4s) extends Controller with AuthElement with AuthConfigImpl {
import Responses._
import Scraper._
import json4s._
implicit val formats = DefaultFormats
def station(lineId: String, pageName: String) = Action { implicit req =>
val url = s"${Host}/newdata/ekijikoku/${lineId}/${pageName}.htm"
val xml = loadXML(url)
StationPage.fromXml(xml) match {
case Left(str) => notFound(str)
case Right(station) =>
val trains = station.trains.filterNot(_.add.contains("?"))
Ok(Extraction.decompose(trains.map(_.replaceAbbr(station.abbr))))
}
}
def timeTable(lineId: String, pageName: String) = StackAction(AuthorityKey -> Administrator) { implicit req =>
???
}
def train(lineId: String, trainId: String) = StackAction(AuthorityKey -> Administrator) { implicit req =>
val address = s"/newdata/detail/${lineId}/${trainId}.htm"
TrainPage.fromXML(loadXML(s"${Host}${address}"), address) match {
case Left(str) => notFound(str)
case Right(train) => Ok(Extraction.decompose(train))
}
}
private[this] def loadXML(url: String): NodeSeq = {
val html = scala.io.Source.fromURL(url)(Codec("Shift_JIS")).mkString
Html5.parse(html) openOr NodeSeq.Empty
}
}
object Scraper {
val Host = "http://www.ekikara.jp"
}
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:55,代码来源:Scraper.scala
示例11: DeputadosResource
//设置package包名称以及导入依赖的类
package com.nakamura.camara.deputados
import javax.ws.rs.container.{AsyncResponse, Suspended}
import javax.ws.rs._
import javax.ws.rs.core.MediaType
import com.codahale.metrics.annotation.{ExceptionMetered, Timed}
import com.nakamura.camara.deputados.deputado.Deputado
import org.json4s.Extraction
import org.json4s.jackson.JsonMethods._
import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Success}
@Path("/deputados/")
class DeputadosResource(service: DeputadosService,
implicit val executionContext: ExecutionContext) {
implicit val formats = org.json4s.DefaultFormats
@GET
@Timed
@ExceptionMetered
@Path("/fetch")
@Produces(Array(MediaType.APPLICATION_JSON))
def fetchDeputados(@Suspended asyncResponse: AsyncResponse): Unit = {
val future: Future[Seq[Deputado]] = service.getDeputados() match {
case Success(deputados) => Future(deputados)
case Failure(err) => Future(throw new Error("Failed."))
}
future onSuccess { case response: Seq[Deputado] =>
asyncResponse.resume(compact(render(Extraction.decompose(response))))
}
future onFailure { case t: Throwable =>
asyncResponse.resume(t)
}
}
}
开发者ID:akionakamura,项目名称:camara,代码行数:37,代码来源:DeputadosResource.scala
示例12: 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
示例13: 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
示例14: 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
示例15: Json
//设置package包名称以及导入依赖的类
package com.paypal.risk.smunf.util
import org.json4s.DefaultFormats
import org.json4s.Extraction
import org.json4s.jackson.JsonMethods
object Json {
def toJsonString(in: Any): String = {
implicit val formats = DefaultFormats
JsonMethods.compact(JsonMethods.render(Extraction.decompose(in)))
}
def toPrettyJsonString(in: Any): String = {
implicit val formats = DefaultFormats
JsonMethods.pretty(JsonMethods.render(Extraction.decompose(in)))
}
}
开发者ID:yanlzhang8936,项目名称:Smunf,代码行数:19,代码来源:Json.scala
示例16: negotiateAction
//设置package包名称以及导入依赖的类
package controllers
import org.json4s.{Extraction, _}
import play.api.mvc._
import scala.concurrent.{ExecutionContext, Future}
import org.json4s._
import org.json4s.Xml.toXml
import org.json4s.native.JsonMethods.{render => jsonRender, _}
import play.api.http.ContentTypes
trait ContentNegotiation extends AcceptExtractors with Rendering with Results {
import ExecutionContext.Implicits.global
def negotiateAction[M](block: Request[AnyContent] => Future[Content[M]])
(implicit formats: Formats): Action[AnyContent] = Action.async { implicit request =>
block(request) map { result =>
val repr: JValue = serialize(result.model)
render {
case Accepts.Xml() => xmlResult(repr, result.status)
case Accepts.Json() => jsonResult(repr, result.status)
}
}
}
private def xmlResult(repr: JValue, status: Int)
(implicit request: Request[AnyContent]) =
Results.Status(status)(toXml(repr).toString).as(ContentTypes.XML)
private def jsonResult(repr: JValue, status: Int)
(implicit request: Request[AnyContent]) =
Results.Status(status)(compact(jsonRender(repr))).as(ContentTypes.JSON)
private def serialize[M](model: M)(implicit formats: Formats): JValue =
Extraction.decompose(model)
}
final case class Content[M](model: M, status: Int = 200)
开发者ID:seglo,项目名称:play-content-negotiation,代码行数:40,代码来源:ContentNegotiation.scala
示例17: UserController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.{Inject, Singleton}
import authes.AuthConfigImpl
import authes.Role.NormalUser
import com.github.tototoshi.play2.json4s.native.Json4s
import jp.t2v.lab.play2.auth.AuthElement
import models.User
import org.json4s.{DefaultFormats, Extraction}
import play.api.mvc._
import queries.CreateUser
import scalikejdbc._
@Singleton
class UserController @Inject()(json4s: Json4s) extends Controller with AuthElement with AuthConfigImpl {
import json4s._
import Responses._
implicit def formats = DefaultFormats
def show() = StackAction(AuthorityKey -> NormalUser) { implicit req =>
Ok(Extraction.decompose(loggedIn.minimal))
}
def list(public: Boolean) = Action {
import models.Aliases.u
val users = if(public) User.findAllBy(sqls.eq(u.public, true))
else User.findAll()
Ok(Extraction.decompose(users.map(_.minimal)))
}
def showMin(id: Long) = Action {
User.findById(id).fold(notFound("player")) { user =>
Ok(Extraction.decompose(user.minimal))
}
}
def createAccount() = Action(json) { req =>
req.body.extractOpt[CreateUser].fold(JsonParseError) { user =>
User.create(user.user())(AutoSession)
Success
}
}
def public(next: Boolean) = StackAction(AuthorityKey -> NormalUser) { implicit req =>
val result = User.updateById(loggedIn.id).withAttributes('public -> next)(AutoSession)
if(result > 0) Success else InternalServerError
}
}
开发者ID:ponkotuy,项目名称:aggregate-exif,代码行数:51,代码来源:UserController.scala
示例18: ExifController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.{Inject, Singleton}
import authes.AuthConfigImpl
import authes.Role.NormalUser
import com.github.tototoshi.play2.json4s.native.Json4s
import com.ponkotuy.queries.Exif
import jp.t2v.lab.play2.auth.AuthElement
import models.{ExifSerializer, Image}
import org.json4s.{DefaultFormats, Extraction}
import org.json4s.ext.JodaTimeSerializers
import play.api.Logger
import play.api.mvc.{Action, Controller}
import scalikejdbc._
@Singleton
class ExifController @Inject()(json4s: Json4s) extends Controller with AuthElement with AuthConfigImpl {
import Responses._
import json4s._
implicit val formats = DefaultFormats ++ JodaTimeSerializers.all
def upload() = StackAction(json, AuthorityKey -> NormalUser) { implicit req =>
req.body.extractOpt[Exif].fold(JsonParseError){ exif =>
DB localTx { implicit session =>
if(new ExifSerializer(exif).save(loggedIn.id).exists(0 < _)) {
Logger.info(s"Insert ${exif.fileName}")
Success
} else BadRequest("Duplicated?")
}
}
}
def list(userId: Long) = Action {
import models.Aliases.i
Ok(Extraction.decompose(Image.findAllBy(sqls.eq(i.userId, userId))))
}
}
开发者ID:ponkotuy,项目名称:aggregate-exif,代码行数:40,代码来源:ExifController.scala
示例19: TestJWTServlet
//设置package包名称以及导入依赖的类
package com.sigurdsoftware.jwt4scalatra
import org.junit.runner.RunWith
import org.specs2.runner.JUnitRunner
import org.scalatra.test.specs2.MutableScalatraSpec
import javax.servlet.http.HttpServletRequest
import org.json4s.Formats
import org.json4s.DefaultFormats
import org.scalatra.ScalatraServlet
import authentikat.jwt.JwtHeader
import authentikat.jwt.JwtClaimsSet
import org.json4s.Extraction
import authentikat.jwt.JsonWebToken
class TestJWTServlet extends ScalatraServlet with JWTSupport{
get("/"){
val u = jwtAuth
u.userid
}
}
@RunWith(classOf[JUnitRunner])
class JWTAuthSpec extends MutableScalatraSpec {
implicit val jsonFormats: Formats = DefaultFormats
addServlet(classOf[TestJWTServlet], "/*")
"requests" should{
val authkey = "Authorization"
val header = JwtHeader("HS256")
val claimsSet = JwtClaimsSet(Extraction.decompose(JWTClaims(((System.currentTimeMillis/1000)+1000).toString, 1, "tim")))
val tok = JsonWebToken(header, claimsSet, "secretkeybatterydowntownhorsegirrafe")
"401 when no auth header" in {
get("/") {status === 401}
}
"401 when bad scheme" in {
get(uri="/", headers=Map(authkey -> "BadScheme")) {status === 401}
}
"403 when good scheme but bad value" in{
get(uri="/", headers=Map(authkey -> "Bearer Nonsense")) {status === 403}
}
"403 when good scheme but blank value" in{
get(uri="/", headers=Map(authkey -> "Bearer ")) {status === 403}
}
"get user id back with 200 when valid header" in {
get(uri="/", headers=Map(authkey -> s"Bearer $tok")){
status === 200 and response.body === "1"
}
}
}
}
开发者ID:gnomff,项目名称:JWT4Scalatra,代码行数:51,代码来源:JWTAuthSpec.scala
示例20: JsonSerializer
//设置package包名称以及导入依赖的类
package com.github.gigurra.scalego.serialization.json
import org.json4s.JsonAST.JValue
import org.json4s.{DefaultFormats, Extraction, Formats}
import org.json4s.jackson.JsonMethods.{compact, parse}
import org.json4s.jackson.JsonMethods.{pretty => prty}
import Extraction.{decompose, extract}
import com.github.gigurra.scalego.core.{ECS, IdTypes}
import com.github.gigurra.scalego.serialization.{ECSSerializer, IdTypeMapper, KnownSubTypes}
import ECSSerializer._
case class JsonSerializer[T_IdTypes <: IdTypes](knownSubtypes: KnownSubTypes = KnownSubTypes.empty,
jsonFormats: Formats = DefaultFormats)
(implicit systemIdMapper: IdTypeMapper[T_IdTypes#SystemId], entityIdMapper: IdTypeMapper[T_IdTypes#EntityId]) {
private val serializer = new ECSSerializer[JValue, T_IdTypes](new JsonMapper[T_IdTypes](jsonFormats), knownSubtypes)
implicit class SerializableOps(ecs: ECS[T_IdTypes]) {
def toJsonAst: JValue = {
val map = serializer.SerializableECSOpsWrite(ecs).toSerializable
decompose(map)(jsonFormats)
}
def toJson(pretty: Boolean = false): String = {
if (pretty) prty(toJsonAst)
else compact(toJsonAst)
}
def appendJson(json: String): Unit = {
appendJsonAst(parse(json))
}
def appendJsonAst(json: JValue): Unit = {
val intermediaryFormat = extract[SerializableEcs[JValue]](json)(jsonFormats, implicitly[Manifest[SerializableEcs[JValue]]])
serializer.SerializableECSOpsRead(ecs).append(intermediaryFormat)
}
}
}
开发者ID:GiGurra,项目名称:scalego,代码行数:41,代码来源:JsonSerializer.scala
注:本文中的org.json4s.Extraction类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论