• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala JsObject类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中play.api.libs.json.JsObject的典型用法代码示例。如果您正苦于以下问题:Scala JsObject类的具体用法?Scala JsObject怎么用?Scala JsObject使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了JsObject类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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))
    }
  }
} 
开发者ID:slideon,项目名称:Scrawler-frontend,代码行数:56,代码来源:HomeController.scala


示例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)
  }
  
} 
开发者ID:Rheriel,项目名称:LightHouse,代码行数:52,代码来源:PostRepo.scala


示例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()
        }
    })

} 
开发者ID:suya55,项目名称:kakaoYellowIdBot,代码行数:39,代码来源:Slick.scala


示例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
  }
} 
开发者ID:evolution-gaming,项目名称:akka-http-documenteddsl,代码行数:31,代码来源:OutDocumentation.scala


示例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 
开发者ID:evolution-gaming,项目名称:akka-http-documenteddsl,代码行数:55,代码来源:JsonSchema.scala


示例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)
  }
} 
开发者ID:aphexcx,项目名称:iconoclast-api,代码行数:54,代码来源:Repo.scala


示例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))
} 
开发者ID:Sengab-platform,项目名称:backend,代码行数:62,代码来源:WithdrawHandler.scala


示例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
    }

} 
开发者ID:tmccartan,项目名称:rest-akka-cluster,代码行数:58,代码来源:GraphQLController.scala


示例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
      ))
    }
  }

} 
开发者ID:aNkM,项目名称:homework-pokemon,代码行数:55,代码来源:PokemonController.scala


示例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)
  }
} 
开发者ID:falsewasnottrue,项目名称:auth-jwt,代码行数:41,代码来源:AuthController.scala


示例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")
    }
  }
} 
开发者ID:falsewasnottrue,项目名称:auth-jwt,代码行数:25,代码来源:AuthService.scala


示例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
  }

} 
开发者ID:falsewasnottrue,项目名称:auth-jwt,代码行数:33,代码来源:TokenServiceSpec.scala


示例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>)
  }
} 
开发者ID:unic,项目名称:ScalaWebTest,代码行数:24,代码来源:FindByResourceTypeSpec.scala


示例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])
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:18,代码来源:PluginDefinition.scala


示例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)
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:53,代码来源:AppConversionTest.scala


示例16: JsonProjectorSpec

//设置package包名称以及导入依赖的类
package com.wellfactored.restless.play.json

import com.wellfactored.restless.query.QueryAST.Path
import org.scalatest.{FlatSpec, Matchers}
import play.api.libs.json.{JsObject, Json}

class JsonProjectorSpec extends FlatSpec with Matchers {

  "JsonProjector" should "extract a value from a Json object" in {
    val paths = List(Path("a"))
    val json = Json.parse("""{ "a" : 5 }""").as[JsObject]

    val projector = new JsonProjector[JsObject](paths)
    projector.project(json) shouldBe json
  }

  it should "extract a nested value from a Json Object" in {
    val paths = List(Path("a.b"))
    val json = Json.parse("""{ "a" : { "b" : 5 } }""").as[JsObject]

    val projector = new JsonProjector[JsObject](paths)
    projector.project(json) shouldBe json
  }

  it should "extract one of two values from a Json Object" in {
    val paths = List(Path("a"))
    val json = Json.parse("""{ "a" : 5, "b" : 4 }""").as[JsObject]
    val expected = Json.parse("""{ "a" : 5 }""").as[JsObject]

    val projector = new JsonProjector[JsObject](paths)
    projector.project(json) shouldBe expected
  }

  it should "extract both values from a Json Object" in {
    val paths = List(Path("a"), Path("b"))
    val json = Json.parse("""{ "a" : 5, "b" : 4 }""").as[JsObject]

    val projector = new JsonProjector[JsObject](paths)
    projector.project(json) shouldBe json
  }

  it should "extract a structure from a Json Object" in {
    val paths = List(Path("x"))
    val json = Json.parse("""{ "x" : { "a" : 5, "b" : 4 } }""").as[JsObject]

    val projector = new JsonProjector[JsObject](paths)
    projector.project(json) shouldBe json
  }

  it should "extract and combine two parts of a structure from a Json Object" in {
    val paths = List(Path("x.a"), Path("x.b"))
    val json = Json.parse("""{ "x" : { "a" : 5, "b" : 4, "c" : 3 } }""").as[JsObject]
    val expected = Json.parse("""{ "x" : { "a" : 5, "b" : 4 } }""").as[JsObject]

    val projector = new JsonProjector[JsObject](paths)
    projector.project(json) shouldBe expected
  }

} 
开发者ID:WellFactored,项目名称:restless,代码行数:60,代码来源:JsonProjectorSpec.scala


示例17: TestController

//设置package包名称以及导入依赖的类
package uk.gov.bis.levyApiMock.controllers.security

import play.api.libs.json.{JsBoolean, JsObject, JsString}
import play.api.mvc.{Action, Controller}
import uk.gov.bis.levyApiMock.auth.TOTP

class TestController extends Controller {

  def generateToken(secret: String, ts: Option[Long]) = Action {
    val token = TOTP.generateCodeAtTime(secret, ts.getOrElse(System.currentTimeMillis())).value
    Ok(JsObject(Seq("token" -> JsString(token))))
  }

  def checkToken(secret: String, token: String, ts: Option[Long]) = Action {
    val generatedToken = TOTP.generateCodeAtTime(secret, ts.getOrElse(System.currentTimeMillis())).value

    val valid = generatedToken == token
    Ok(JsObject(Seq("valid" -> JsBoolean(valid))))
  }

} 
开发者ID:UKGovernmentBEIS,项目名称:das-alpha-hmrc-api-mock,代码行数:22,代码来源:TestController.scala


示例18: Busy

//设置package包名称以及导入依赖的类
package models

import play.api.libs.json.{JsObject, JsString, Writes}

sealed trait ConversionStatus

case class Busy() extends ConversionStatus

case class Free() extends ConversionStatus

object ConversionStatus {
  implicit val jobStatusWrites: Writes[models.ConversionStatus] =
    Writes[models.ConversionStatus](s => JsObject(Map(
      "status" -> (s match {
        case Free() => JsString("free")
        case Busy() => JsString("busy")
      })
    )))
} 
开发者ID:kuhnuri,项目名称:kuhnuri-worker,代码行数:20,代码来源:ConversionStatus.scala


示例19: Validation

//设置package包名称以及导入依赖的类
package utils

import play.api.Play.current
import play.api.data.validation.ValidationError
import play.api.i18n.Messages
import play.api.i18n.Messages.Implicits._
import play.api.libs.json.Json._
import play.api.libs.json.{JsObject, JsPath, Json}
import play.api.mvc._

import scala.concurrent.Future


object Validation extends Controller {

  def validationError(code: Int)(errors: Seq[(JsPath, Seq[ValidationError])]): Future[Result] = {
    def messageFormat: JsObject = {
      errors.foldLeft(Json.obj()) { (obj, error) =>
        obj ++ Json.obj(error._1.toString().replaceFirst(Constants.Global.SLASH, Constants.Global.EMPTY_STRING) -> error._2.foldLeft(Json.arr()) { (arr, err) =>
          arr :+ Json.obj(Constants.Global.MESSAGE -> Messages(err.message, if (err.args.nonEmpty) err.args.head).toString)
        })
      }
    }
    Future.successful(BadRequest(obj(Constants.Global.STATUS -> code, Constants.Global.ERROR_MESSAGE -> messageFormat)))
  }
} 
开发者ID:satriapribadi,项目名称:satriapribadi.com,代码行数:27,代码来源:Validation.scala


示例20: JsObjectInstances

//设置package包名称以及导入依赖的类
package com.iravid.playjsoncats

import cats.kernel.Eq
import play.api.libs.json.{ Json, JsObject, JsArray }
import cats.Monoid

object JsObjectInstances extends JsObjectInstances
trait JsObjectInstances {
  implicit val jsObjectMonoid: Monoid[JsObject] = new Monoid[JsObject] {
    def empty: JsObject = Json.obj()
    def combine(x: JsObject, y: JsObject): JsObject = x deepMerge y
  }

  implicit val jsObjectEq: Eq[JsObject] = Eq.fromUniversalEquals
}

object JsArrayInstances extends JsArrayInstances
trait JsArrayInstances {
  implicit val jsArrayMonoid: Monoid[JsArray] = new Monoid[JsArray] {
    def empty: JsArray = Json.arr()
    def combine(x: JsArray, y: JsArray): JsArray = x ++ y
  }

  implicit val jsArrayEq: Eq[JsArray] = Eq.fromUniversalEquals
} 
开发者ID:iravid,项目名称:play-json-cats,代码行数:26,代码来源:JsValueInstances.scala



注:本文中的play.api.libs.json.JsObject类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala InputStreamReader类代码示例发布时间:2022-05-23
下一篇:
Scala BufferedReader类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap