本文整理汇总了Scala中play.api.libs.json.JsObject类的典型用法代码示例。如果您正苦于以下问题:Scala JsObject类的具体用法?Scala JsObject怎么用?Scala JsObject使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了JsObject类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: HomeController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject._
import org.slf4j.LoggerFactory
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.{JsObject, JsValue, Json}
import play.api.mvc._
import play.modules.reactivemongo._
import play.modules.reactivemongo.json._
import play.modules.reactivemongo.json.collection.{JSONCollection, _}
import reactivemongo.api.Cursor
import scala.concurrent.Future
@Singleton
class HomeController @Inject() (val reactiveMongoApi: ReactiveMongoApi)
extends Controller with MongoController with ReactiveMongoComponents {
val logger = LoggerFactory.getLogger(this.getClass)
def collection: JSONCollection = db.collection[JSONCollection]("scrawler1")
def index = Action {
Ok(views.html.index(""))
}
def query = Action.async { request =>
val body = request.body
val query = body.asFormUrlEncoded.get("query")
val querySet = query.toSet[String]
val keywords = querySet.flatMap({ string: String =>
string.split(" ")
})
val searchQuery = Json.obj("keywords" -> Json.obj("$in" -> Json.toJson(keywords)))
logger.info(s"Internal query from client: $searchQuery")
val cursor: Cursor[JsObject] = collection.find(searchQuery).cursor[JsObject]
val result: Future[List[JsObject]] = cursor.collect[List]()
val resultJson: Future[JsValue] =
result.map { persons => Json.toJson(persons) }
resultJson.map { results =>
val title = results \\ "title"
val url = results \\ "url"
val description = results \\ "body"
val queryData: Seq[((JsValue, JsValue), JsValue)] = title.zip(url).zip(description)
Ok(views.html.result(queryData))
}
}
}
示例2: find
//设置package包名称以及导入依赖的类
package repos
import scala.concurrent.{ExecutionContext, Future}
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import play.api.libs.json.{JsObject, Json}
import reactivemongo.api.commands.WriteResult
import play.modules.reactivemongo.ReactiveMongoApi
import javax.inject._
import play.modules.reactivemongo.json._
import play.modules.reactivemongo.json.collection.JSONCollection
import reactivemongo.api.ReadPreference
trait PostRepo {
def find() (implicit ec: ExecutionContext): Future[List[JsObject]]
def select(selector: BSONDocument) (implicit ec: ExecutionContext): Future[Option[JsObject]]
def update(selector: BSONDocument, update: BSONDocument) (implicit ec: ExecutionContext): Future[WriteResult]
def remove(document: BSONDocument) (implicit ec: ExecutionContext): Future[WriteResult]
def save(document: BSONDocument) (implicit ec: ExecutionContext): Future[WriteResult]
}
class PostRepoImpl @Inject() (reactiveMongoApi: ReactiveMongoApi) extends PostRepo {
def collection = reactiveMongoApi.db.collection[JSONCollection]("posts");
override def find() (implicit ec: ExecutionContext): Future[List[JsObject]] = {
val genericQueryBuilder = collection.find(Json.obj());
val cursor = genericQueryBuilder.cursor[JsObject](ReadPreference.Primary);
cursor.collect[List]()
}
def select(selector: BSONDocument)(implicit ec: ExecutionContext): Future[Option[JsObject]] = {
collection.find(selector).one[JsObject]
}
def update(selector: BSONDocument, update: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.update(selector,update)
}
def remove(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.remove(document)
}
def save(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.update(BSONDocument("_id" -> document.get("_id").getOrElse(BSONObjectID.generate)), document, upsert = true)
}
}
示例3: Slick
//设置package包名称以及导入依赖的类
package utils
import java.util.Date
import com.fasterxml.jackson.core.JsonParseException
import play.api.Logger
import play.api.db.DB
import play.api.libs.json.{Json, JsObject}
import slick.driver.MySQLDriver.api._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import play.api.Play.current
object Slick extends Slick {
def apply(name: String) = new Slick {
override lazy val DBName = name
}
}
trait Slick {
protected lazy val DBName = "default"
val duration = Duration(5, SECONDS)
implicit def db = Database.forDataSource(DB.getDataSource(DBName))
}
trait ExtMapper {
implicit val date2SqlDate = MappedColumnType.base[Date, java.sql.Timestamp](d => new java.sql.Timestamp(d.getTime), d => new java.util.Date(d.getTime))
implicit val list2String = MappedColumnType.base[List[String], String](array => array.mkString(","), string => string.split(",").toList)
implicit val jsonObjMapper = MappedColumnType.base[JsObject, String](json => json.toString(), s => try {
Json.parse(s).as[JsObject]
} catch {
case e: JsonParseException => {
Logger.error(s"JsObjectMapper Error [data:$s]", e)
Json.obj()
}
})
}
示例4: OutDocumentation
//设置package包名称以及导入依赖的类
package akka.http.documenteddsl.documentation
import akka.http.documenteddsl.documentation.OutDocumentation.Payload._
import akka.http.documenteddsl.documentation.OutDocumentation._
import akka.http.scaladsl.model.StatusCode
import play.api.libs.json.{JsObject, JsValue}
case class OutDocumentation(
success: List[Success] = Nil,
failure: List[Failure] = Nil) {
def :+(r: Payload): OutDocumentation = r match {
case r: Success => copy(success = success :+ r)
case r: Failure => copy(failure = failure :+ r)
}
}
object OutDocumentation {
case class Status(code: Int, detail: String)
object Status {
def apply(statusCode: StatusCode): Status = Status(
statusCode.intValue,
statusCode.reason)
}
sealed trait Payload
object Payload {
case class Success(status: Status, contentType: String, schema: JsObject, example: Option[JsValue]) extends Payload
case class Failure(status: Status, contentType: Option[String], description: Option[String]) extends Payload
}
}
示例5: JsonSchema
//设置package包名称以及导入依赖的类
package akka.http.documenteddsl.documentation
import org.coursera.autoschema.{AutoSchema, TypeMappings}
import play.api.libs.json.{JsObject, Json}
import scala.reflect.runtime.{universe => ru}
import scala.util.control.NonFatal
object JsonSchema {
def resolveSchema[T](implicit t: ru.TypeTag[T], as: AutoSchema): JsObject = {
try as.createSchema[T] catch {
case NonFatal(err) =>
def errPath(ex: Throwable): String = ex.getCause match {
case null => ex.getMessage
case x => "[" + ex.getClass.getSimpleName + "]" + ex.getMessage + ". Caused by: " + errPath(x)
}
Json.obj("error" -> s"$t: ${errPath(err)}")
}
}
val string: JsObject = Json.obj("type" -> "string")
val numeric: JsObject = Json.obj("type" -> "number", "format" -> "number")
val boolean: JsObject = Json.obj("type" -> "boolean")
}
trait DocumentedTypeMappings extends TypeMappings {
import JsonSchema._
override def schemaTypeForScala(typeName: String): Option[JsObject] = {
schemaTypes.get(typeName)
}
private val schemaTypes = Map(
"scala.Nothing" -> Json.obj(),
"scala.Unit" -> Json.obj(),
"org.joda.time.DateTime" -> Json.obj("type" -> "string", "format" -> "date"),
"java.time.ZonedDateTime" -> Json.obj("type" -> "string", "format" -> "date"),
"java.time.LocalDate" -> Json.obj("type" -> "string", "format" -> "date", "pattern" -> localDatePattern),
"java.util.Date" -> Json.obj("type" -> "string", "format" -> "date"),
"java.lang.String" -> string,
"scala.Boolean" -> boolean,
"scala.Int" -> numeric,
"scala.Long" -> numeric,
"scala.Double" -> numeric,
"scala.math.BigInt" -> numeric,
"scala.math.BigDecimal" -> numeric,
"java.util.UUID" -> Json.obj("type" -> "string", "pattern" -> "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$")
)
lazy val localDatePattern = "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
}
object DocumentedTypeMappings extends DocumentedTypeMappings
示例6: find
//设置package包名称以及导入依赖的类
package repos
import javax.inject.Inject
import play.api.libs.json.{JsObject, Json}
import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.json._
import reactivemongo.api.ReadPreference
import reactivemongo.api.commands.WriteResult
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.{ExecutionContext, Future}
trait RepoLike {
def find()(implicit ec: ExecutionContext): Future[List[JsObject]]
def select(selector: BSONDocument)(implicit ec: ExecutionContext): Future[Option[JsObject]]
def update(selector: BSONDocument, update: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult]
def remove(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult]
def save(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult]
}
abstract class Repo @Inject()(reactiveMongoApi: ReactiveMongoApi) extends RepoLike {
val collectionName: String
override def find()(implicit ec: ExecutionContext): Future[List[JsObject]] = {
collection.find(Json.obj())
.cursor[JsObject](ReadPreference.Primary)
.collect[List](100)
}
override def select(selector: BSONDocument)(implicit ec: ExecutionContext): Future[Option[JsObject]] = {
collection.find(selector).one[JsObject]
}
override def update(selector: BSONDocument, update: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.update(selector, update)
}
def collection: JSONCollection = reactiveMongoApi.db.collection[JSONCollection](collectionName)
override def remove(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.remove(document)
}
override def save(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.update(BSONDocument("_id" -> document.get("_id").getOrElse(BSONObjectID.generate)), document, upsert = true)
}
}
示例7: WithdrawHandler
//设置package包名称以及导入依赖的类
package actors.enrollment
import actors.AbstractDBHandler
import actors.AbstractDBHandler.QueryResult
import akka.actor.{ActorRef, Props}
import com.couchbase.client.java.document.json.JsonObject
import helpers.Helper
import helpers.Helper._
import messages.EnrollmentManagerMessages.Withdraw
import models.Response
import models.errors.GeneralErrors.CouldNotParseJSON
import play.api.Logger
import play.api.libs.json.{JsObject, JsString, Json}
class WithdrawHandler(out: ActorRef) extends AbstractDBHandler(out) {
// this is the msg to user when error happens while querying from db
override val ErrorMsg: String = "Withdraw from project failed"
override def receive = {
case Withdraw(userID: String, projectID: String) => Logger.info(s"actor ${self.path} - received msg : ${Withdraw(userID, projectID)}")
executeQuery(DBUtilities.User.removeProjectFromEnrolledProjects(userID, projectID))
case QueryResult(jsonObject) =>
val response = constructResponse(jsonObject)
response match {
case Some(Response(jsonResult)) =>
// get project id as String
val projectID = (jsonResult \ "project_id").as[String]
executeQuery(DBUtilities.Project.remove1FromProjectEnrollmentsCount(projectID))
// get statsID
val statsID = Helper.StatsIDPrefix + trimEntityID(projectID)
executeQuery(DBUtilities.Stats.remove1FromStatsEnrollmentsCount(statsID))
out ! Response(jsonResult)
case None =>
out ! CouldNotParseJSON("failed to withdraw user",
"couldn't parse json retrieved from the db ", this.getClass.toString)
}
}
override def constructResponse(jsonObject: JsonObject): Option[Response] = {
try {
val parsedJson = Json.parse(jsonObject.toString)
//add project url
val url = addField(parsedJson.as[JsObject], "url", helpers.Helper.ProjectPath + (parsedJson \ "projectId").as[String])
val project = JsObject(Seq(
"project_id" -> JsString((parsedJson \ "projectId").as[String]),
"url" -> JsString((url \ "url").as[String])))
Some(Response(project))
} catch {
case _: Exception => None
}
}
}
object WithdrawHandler {
def props(out: ActorRef): Props = Props(new WithdrawHandler(out: ActorRef))
}
示例8: GraphQLController
//设置package包名称以及导入依赖的类
package graphql
import controllers.BaseController
import play.api.libs.json.{Json, JsObject}
import play.api.mvc._
import sangria.execution.{ErrorWithResolver, QueryAnalysisError, Executor}
import sangria.parser.{SyntaxError, QueryParser}
import sangria.marshalling.playJson._
import service.{AddressService, PaymentMethodService, SessionService}
import scala.concurrent.Future
import scala.util.{Failure, Success}
class GraphQLController (sessionService: SessionService, paymentMethodService: PaymentMethodService, addressService: AddressService) extends BaseController {
def graphql(query: Option[String], variables: Option[String], operation: Option[String]) = Action.async {
implicit request => {
val resolvedQuery = request.method match {
case "POST" => request.body.asText.get
case "GET" => query.get
case _ => "" //let it throw the syntax error
}
println(s"Recieved graph ql query = $resolvedQuery method ${request.method}" )
executeQuery(resolvedQuery, variables map parseVariables, operation)
}}
private def parseVariables(variables: String) =
if (variables.trim == "" || variables.trim == "null") Json.obj() else Json.parse(variables).as[JsObject]
private def executeQuery(query: String, variables: Option[JsObject], operation: Option[String]) =
QueryParser.parse(query) match {
// query parsed successfully, time to execute it!
case Success(queryAst) => Executor.execute (
SchemaDefinition.CheckoutSchema, queryAst, SessionRepo(sessionService , paymentMethodService, addressService),
operationName = operation
).map(Ok(_)).recover {
case error: QueryAnalysisError ? BadRequest(error.resolveError)
case error: ErrorWithResolver ? InternalServerError(error.resolveError)
}
// can't parse GraphQL query, return error
case Failure(error: SyntaxError) ?
Future.successful(BadRequest(Json.obj(
"syntaxError" ? error.getMessage,
"locations" ? Json.arr(Json.obj(
"line" ? error.originalError.position.line,
"column" ? error.originalError.position.column)))))
case Failure(error) ?
throw error
}
}
示例9: PokemonController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import play.api.Logger
import play.api.cache._
import play.api.libs.json.{JsArray, JsObject, JsValue}
import play.api.mvc._
import shared._
class PokemonController @Inject() (cache: CacheApi) extends Controller {
def postTweets = Action(parse.json) { implicit req =>
Ok(SharedTwitterAPICalls.getLastTweets(req.body.toString()))
}
// Name, URL, Slot/Base_stat
def parsePokemonWithParameter(param: String, param2: String, types: JsArray): Seq[((String, String), Int)] = {
(types \\ param).map(x => ( (x \ "name").as[String], (x \ "url").as[String] ))
.zip( (types \\ param2).map(x => x.as[Int]) )
}
def index(name: String) = Action {
SharedPokemonList.set(cache.getOrElse[Seq[(String,String)]]("pokemonList") {
val list = SharedPokemonAPICalls.initializePokemonList
cache.set("pokemonList", list)
list
})
val foundPokemons = SharedPokemonList.get.filter(x => x._1 == name)
if (foundPokemons == Seq.empty[(String, String)])
NotFound(views.html.notFoundPage(name))
else {
val foundPokemon = foundPokemons.head
val result: JsValue = SharedPokemonAPICalls.getPokemonById(foundPokemon._2).as[JsObject] - "moves"
SharedPokemonActive.set(result)
Ok(views.html.pokemon(
(result \ "sprites" \ "front_default").as[String],
(result \ "name").as[String],
(result \ "base_experience").as[Int],
parsePokemonWithParameter("type", "slot", (result \ "types").as[JsArray] ),
parsePokemonWithParameter("ability", "slot", (result \ "abilities").as[JsArray] ),
parsePokemonWithParameter("stat", "base_stat", (result \ "stats").as[JsArray] ),
SharedTwitterAPICalls.getLastTweets((result \ "name").as[String]),
60000,
routes.PokemonController.postTweets
))
}
}
}
示例10: AuthController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Singleton
import play.api.libs.json.{JsObject, Json}
import play.api.mvc.{Action, Controller}
import services.{MockAuthService, TokenService}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
@Singleton
class AuthController extends Controller {
// TODO inject
val tokenService = new TokenService("secret")
val authService = new MockAuthService
def login = Action.async(parse.json) { implicit request =>
val user = (request.body \ "username").as[String]
val password = (request.body \ "password").as[String]
println(s"login: $user: $password")
val header: JsObject = Json.obj(
"alg" -> "HS256",
"typ" -> "JWT"
)
authService.auth(user, password).map { payload =>
val token = tokenService.encode(header, payload)
Ok(token)
} recover { case exception =>
Unauthorized
}
}
def logout = Action.async {
Future.successful(Ok)
}
}
示例11: auth
//设置package包名称以及导入依赖的类
package services
import play.api.libs.json.{JsObject, Json}
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
trait AuthService {
def auth(user: String, password: String): Future[JsObject]
}
class MockAuthService extends AuthService {
def auth(user: String, password: String): Future[JsObject] = Future {
if (password == "1234") {
Json.obj(
"sub" -> "1234567890",
"name" -> user,
"admin" -> true
)
} else {
throw new IllegalStateException("not authenticated")
}
}
}
示例12: TokenServiceSpec
//设置package包名称以及导入依赖的类
package services
import org.scalatest.{FlatSpec, Matchers}
import play.api.libs.json.{JsObject, Json}
class TokenServiceSpec extends FlatSpec with Matchers {
trait Env {
val secret = "secret"
val tokenService = new TokenService(secret)
val header: JsObject = Json.obj(
"alg" -> "HS256",
"typ" -> "JWT"
)
val payload: JsObject = Json.obj(
"sub" -> "1234567890",
"name" -> "John Doe",
"admin" -> true
)
val jwt: String =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9." +
"eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9." +
"TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"
}
"Token Service" should "encode a message" in new Env {
tokenService.encode(header, payload) shouldBe jwt
}
}
示例13: FindByResourceTypeSpec
//设置package包名称以及导入依赖的类
package org.scalawebtest.integration.aem
import org.scalawebtest.aem.PageProperties
import org.scalawebtest.core.gauge.HtmlGauge.fits
import org.scalawebtest.integration.extensions.aem.AemModuleScalaWebTestBaseSpec
import play.api.libs.json.{JsObject, JsValue}
class FindByResourceTypeSpec extends AemModuleScalaWebTestBaseSpec with PageProperties {
path = "/aem/geometrixx-outdoors/en/company/our-story.html"
case class ContentPage(pageProperties: JsValue) {
def sidebarParsys: JsObject = (pageProperties \ "jcr:content" \ "sidebar").as[JsObject]
def sidebarImageAltText: String = {
val sidebarImages = sidebarParsys findByResourceType "foundation/components/image"
(sidebarImages.head \ "alt").as[String]
}
}
"Content page" should "have the correct alt text in the sidebar image" in {
val contentPage = ContentPage(pageProperties)
fits(<img alt={contentPage.sidebarImageAltText}></img>)
}
}
示例14: PluginDefinition
//设置package包名称以及导入依赖的类
package mesosphere.marathon.core.plugin
import play.api.libs.json.JsObject
case class PluginDefinition(
id: String,
plugin: String,
implementation: String,
tags: Option[Set[String]],
configuration: Option[JsObject],
info: Option[JsObject])
case class PluginDefinitions(plugins: Seq[PluginDefinition])
object PluginDefinitions {
lazy val None = PluginDefinitions(Seq.empty[PluginDefinition])
}
示例15: AppConversionTest
//设置package包名称以及导入依赖的类
package mesosphere.marathon
package raml
import mesosphere.FunTest
import mesosphere.marathon.api.v2.json.Formats
import mesosphere.marathon.core.health.{ MarathonHttpHealthCheck, PortReference }
import mesosphere.marathon.state.{ AppDefinition, BackoffStrategy, FetchUri, PathId }
import play.api.libs.json.{ JsObject, Json }
import org.apache.mesos.{ Protos => Mesos }
class AppConversionTest extends FunTest {
test("An app is written to json and can be read again via formats") {
Given("An app")
val constraint = Protos.Constraint.newBuilder().setField("foo").setOperator(Protos.Constraint.Operator.CLUSTER).build()
val app = AppDefinition(
id = PathId("/test"),
cmd = Some("test"),
user = Some("user"),
env = Map("A" -> state.EnvVarString("test")),
instances = 23,
resources = Resources(),
executor = "executor",
constraints = Set(constraint),
fetch = Seq(FetchUri("http://test.this")),
portDefinitions = Seq(state.PortDefinition(123), state.PortDefinition(234)),
requirePorts = true,
backoffStrategy = BackoffStrategy(),
container = Some(state.Container.Docker(
volumes = Seq(state.DockerVolume("/container", "/host", Mesos.Volume.Mode.RW)),
image = "foo/bla",
network = Some(Mesos.ContainerInfo.DockerInfo.Network.BRIDGE),
portMappings = Seq(state.Container.PortMapping(12, Some(23), 123)),
privileged = true
)),
healthChecks = Set(MarathonHttpHealthCheck(portIndex = Some(PortReference.ByIndex(0)))),
readinessChecks = Seq(core.readiness.ReadinessCheck()),
acceptedResourceRoles = Set("*")
)
When("The app is translated to json and read back from formats")
val json = Json.toJson(app.toRaml[App])
//filter out values that are written, but are not expected to read back
//TODO: filtering is not needed, once we have the raml reads functionality
val doNotRender = Set("uris", "ports", "version", "versionInfo")
val cleanJson = JsObject(json.as[JsObject].value.filterKeys(field => !doNotRender(field)).toSeq)
val readApp = cleanJson.as[AppDefinition](Formats.AppDefinitionReads).copy(versionInfo = app.versionInfo)
Then("The app is identical")
readApp should be(app)
}
}