本文整理汇总了Scala中play.api.libs.json.JsValue类的典型用法代码示例。如果您正苦于以下问题:Scala JsValue类的具体用法?Scala JsValue怎么用?Scala JsValue使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了JsValue类的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: UserActor
//设置package包名称以及导入依赖的类
package actors
import akka.actor.Actor
import akka.actor.ActorLogging
import akka.event.LoggingReceive
import play.api.libs.json.JsValue
import play.api.libs.json.Json
import akka.actor.ActorRef
import akka.actor.Props
import scala.xml.Utility
class UserActor(uid: String, board: ActorRef, out: ActorRef) extends Actor with ActorLogging {
override def preStart() = {
BoardActor() ! Subscribe
}
def receive = LoggingReceive {
case Message(muid, s) if sender == board => {
val js = Json.obj("type" -> "message", "uid" -> muid, "msg" -> s)
out ! js
}
case js: JsValue => (js \ "msg").validate[String] map { Utility.escape(_) } map { board ! Message(uid, _ ) }
case other => log.error("unhandled: " + other)
}
}
object UserActor {
def props(uid: String)(out: ActorRef) = Props(new UserActor(uid, BoardActor(), out))
}
示例3: serialize
//设置package包名称以及导入依赖的类
package com.commodityvectors.snapshotmatchers.playJson
import com.commodityvectors.snapshotmatchers.{SnapshotLoader, SnapshotMessages, SnapshotSerializer}
import org.scalactic.Equality
import org.scalatest.matchers.{MatchResult, Matcher}
import play.api.libs.json.{JsValue, Json, Reads}
trait PlayJsonSnapshotMatcher extends SnapshotLoader with SnapshotMessages {
implicit lazy val playJsonSerializer = new SnapshotSerializer[JsValue] {
override def serialize(in: JsValue): String = Json.prettyPrint(in)
}
class JsonDeserializerShouldMatch[T](in: T)(implicit reads: Reads[T], equals: Equality[T]) extends Matcher[String] {
override def apply(explicitId: String): MatchResult = {
loadSnapshot(explicitId) match {
case Some(content) =>
val parsed = Json.parse(content).as[T]
val isEquals = equals.areEqual(parsed, in)
MatchResult(isEquals, errorMessage(in.toString, parsed.toString), ContentsAreEqual)
case None => MatchResult(matches = false, s"Could not find snapshot for id: $explicitId", ContentsAreEqual)
}
}
}
def deserializeAs[T](in: T)(implicit reads: Reads[T], equals: Equality[T]) = new JsonDeserializerShouldMatch[T](in)
}
示例4: SuccessfulOut
//设置package包名称以及导入依赖的类
package akka.http.documenteddsl.directives
import akka.http.documenteddsl.documentation.RouteDocumentation
import akka.http.scaladsl.model.{ContentType, StatusCode, StatusCodes}
import akka.http.scaladsl.server.Directive
import org.coursera.autoschema.AutoSchema
import play.api.libs.json.{JsValue, Writes}
import scala.reflect.runtime.{universe => ru}
trait UnmarshallingDDirectives {
final class SuccessfulOut[T : ru.TypeTag](status: StatusCode, example: Option[JsValue]) extends DDirective0 {
def describe(w: RouteDocumentation)(implicit as: AutoSchema): RouteDocumentation = w.outSuccess[T](status.intValue, example)
def delegate = Directive.Empty
}
final class ErrorOut(status: StatusCode, contentType: Option[String], description: Option[String]) extends DDirective0 {
def describe(w: RouteDocumentation)(implicit as: AutoSchema): RouteDocumentation = w.outError(status, contentType, description)
def delegate = Directive.Empty
}
object Out {
def apply[T : ru.TypeTag]: SuccessfulOut[T] = new SuccessfulOut(StatusCodes.OK, None)
def apply[T : ru.TypeTag](status: StatusCode): SuccessfulOut[T] = new SuccessfulOut(status, None)
def apply[T : ru.TypeTag](example: T)(implicit writes: Writes[T]): SuccessfulOut[T] = new SuccessfulOut(StatusCodes.OK, Some(writes writes example))
def apply[T : ru.TypeTag](status: StatusCode, example: T)(implicit writes: Writes[T]): SuccessfulOut[T] = new SuccessfulOut(status, Some(writes writes example))
def success(status: StatusCode): SuccessfulOut[Nothing] = new SuccessfulOut(status, None)
def error(status: StatusCode): ErrorOut = new ErrorOut(status, None, None)
def apply(status: StatusCode, description: String): ErrorOut = new ErrorOut(status, None, Some(description))
def apply(status: StatusCode, contentType: ContentType, description: String): ErrorOut = new ErrorOut(status, Some(contentType.toString()), Some(description))
}
}
object UnmarshallingDDirectives extends UnmarshallingDDirectives
示例5: PreprocessedFromStringUnmarshaller
//设置package包名称以及导入依赖的类
package akka.http.documenteddsl
import akka.http.scaladsl.marshallers.playjson.PlayJsonSupport.PlayJsonError
import akka.http.scaladsl.model.MediaTypes.`application/json`
import akka.http.scaladsl.server.{RejectionError, ValidationRejection}
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, FromStringUnmarshaller, Unmarshaller}
import akka.util.ByteString
import play.api.libs.json.{JsError, JsValue, Json, Reads}
class PreprocessedFromStringUnmarshaller[T](sanitize: Preprocess[String], _fsu: FromStringUnmarshaller[T]) {
implicit val fsu: FromStringUnmarshaller[T] = Unmarshaller withMaterializer {
implicit ec =>
implicit mat =>
string =>
_fsu(sanitize(string))
}
}
object PreprocessedFromStringUnmarshaller {
implicit def unmarshaller[T](implicit sanitize: Preprocess[String] = Preprocess.identity, fsu: FromStringUnmarshaller[T]): PreprocessedFromStringUnmarshaller[T] = {
new PreprocessedFromStringUnmarshaller(sanitize, fsu)
}
}
class PreprocessedFromEntityUnmarshaller[T](sanitize: Preprocess[JsValue], reads: Reads[T]) {
private val jsonStringUnmarshaller =
Unmarshaller.byteStringUnmarshaller
.forContentTypes(`application/json`)
.mapWithCharset {
case (ByteString.empty, _) => throw Unmarshaller.NoContentException
case (data, charset) => data.decodeString(charset.nioCharset.name)
}
implicit val fsu: FromEntityUnmarshaller[T] = jsonStringUnmarshaller map { data =>
val json = sanitize(Json parse data)
reads reads json recoverTotal { error =>
throw RejectionError(ValidationRejection(JsError.toJson(error).toString, Some(PlayJsonError(error))))
}
}
}
object PreprocessedFromEntityUnmarshaller {
implicit def unmarshaller[T](implicit sanitize: Preprocess[JsValue] = Preprocess.identity, reads: Reads[T]): PreprocessedFromEntityUnmarshaller[T] = {
new PreprocessedFromEntityUnmarshaller(sanitize, reads)
}
}
trait Preprocess[T] {
def apply(x: T): T
}
object Preprocess {
def identity[T]: Preprocess[T] = new Preprocess[T] {
override def apply(x: T): T = x
}
}
示例6: 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
}
}
示例7: OpenIdInfoQueries
//设置package包名称以及导入依赖的类
package models.queries
import com.mohiva.play.silhouette.api.LoginInfo
import com.mohiva.play.silhouette.impl.providers.OpenIDInfo
import jdub.async.{ Row, Statement }
import jdub.async.queries.BaseQueries
import org.joda.time.LocalDateTime
import play.api.libs.json.{ JsValue, Json }
object OpenIdInfoQueries extends BaseQueries[OpenIDInfo] {
override protected val tableName = "openid_info"
override protected val columns = Seq("provider", "key", "id", "attributes", "created")
override protected val idColumns = Seq("provider", "key")
override protected val searchColumns = Seq("key")
val getById = GetById
val removeById = RemoveById
case class CreateOpenIdInfo(l: LoginInfo, o: OpenIDInfo) extends Statement {
override val sql = insertSql
override val values = Seq(l.providerID, l.providerKey) ++ toDataSeq(o)
}
case class UpdateOpenIdInfo(l: LoginInfo, o: OpenIDInfo) extends Statement {
override val sql = s"update $tableName set id = ?, attributes = ?, created = ? where provider = ? and key = ?"
val attributes = Json.prettyPrint(Json.toJson(o.attributes))
override val values = toDataSeq(o) ++ Seq(l.providerID, l.providerKey)
}
override protected def fromRow(row: Row) = {
val id = row.as[String]("id")
val attributesString = row.as[String]("attributes")
val attributes = Json.parse(attributesString).as[Map[String, JsValue]].map(x => x._1 -> x._2.as[String])
OpenIDInfo(id, attributes)
}
override protected def toDataSeq(o: OpenIDInfo) = {
val attributes = Json.prettyPrint(Json.toJson(o.attributes))
Seq(o.id, attributes, new LocalDateTime())
}
}
示例8: Utility
//设置package包名称以及导入依赖的类
package com.galacticfog.gestalt.lambda.impl
import io.vertx.core.json.JsonObject
//import play.api.Logger
import play.api.libs.json.{Json, JsValue}
object Utility {
def convert( json : JsValue ) : JsonObject = {
new JsonObject( Json.stringify( json ) )
}
def stripTrailingSlash( path : String ) : String = {
println( "before slash strip: " + path )
val after = """/$""".r.replaceAllIn( path, "" )
println( "after slash strip : " + after )
after
}
}
示例9: TemplateBody
//设置package包名称以及导入依赖的类
package models.project
import models.project.Templates._
import play.api.libs.functional.syntax._
import play.api.libs.json.{JsValue, Json, Reads, Writes}
trait TemplateBody
object TemplateBody {
implicit val tempBodyR: Reads[TemplateBody] = Json.format[TemplateOne].map(x => x: TemplateBody) or
Json.format[TemplateTwo].map(x => x: TemplateBody) or
Json.format[TemplateThree].map(x => x: TemplateBody) or
Json.format[TemplateFour].map(x => x: TemplateBody)
implicit val tempBodyW = new Writes[TemplateBody] {
def writes(c: TemplateBody): JsValue = {
c match {
case m: TemplateOne => Json.toJson(m)
case m: TemplateTwo => Json.toJson(m)
case m: TemplateThree => Json.toJson(m)
case m: TemplateFour => Json.toJson(m)
case _ => Json.obj("error" -> "wrong Json")
}
}
}
}
示例10: ContributionData
//设置package包名称以及导入依赖的类
package models.contribution
import models.contribution.ContributionDataTypes.{ContributionDataTypeFour, ContributionDataTypeOne, ContributionDataTypeThree, ContributionDataTypeTwo}
import play.api.libs.functional.syntax._
import play.api.libs.json.{JsValue, Json, Reads, Writes}
trait ContributionData
object ContributionData {
implicit val tempBodyR: Reads[ContributionData] = Json.format[ContributionDataTypeOne].map(x => x: ContributionData) or
Json.format[ContributionDataTypeThree].map(x => x: ContributionData) or
Json.format[ContributionDataTypeFour].map(x => x: ContributionData) or
Json.format[ContributionDataTypeTwo].map(x => x: ContributionData)
implicit val tempBodyW = new Writes[ContributionData] {
def writes(c: ContributionData): JsValue = {
c match {
case m: ContributionDataTypeOne => Json.toJson(m)
case m: ContributionDataTypeTwo => Json.toJson(m)
case m: ContributionDataTypeThree => Json.toJson(m)
case m: ContributionDataTypeFour => Json.toJson(m)
case _ => Json.obj("error" -> "wrong Json")
}
}
}
}
示例11: MiscEndpointTests
//设置package包名称以及导入依赖的类
package uk.co.appministry.scathon.client
import uk.co.appministry.scathon.models.v2.GetInfoResponse
import com.twitter.finagle.http.Status
import play.api.libs.json.JsValue
class MiscEndpointTests extends TestBase {
"Misc Endpoints" should {
"receive JsValue for metrics endpoint" in {
whenReady( client.metrics() ) { value =>
value shouldBe a[JsValue]
}
}
"receive Ok for ping endpoint" in {
whenReady( client.ping() ) { status =>
status shouldBe( Status.Ok )
}
}
"receive server info from getInfo endpoint" in {
whenReady( client.getInfo() ) { response =>
response shouldBe a[GetInfoResponse]
}
}
}
}
示例12: Status
//设置package包名称以及导入依赖的类
package domain
import play.api.libs.json.{Format, JsString, JsSuccess, JsValue}
object Status extends Enumeration {
type Status = Value
val Inactive = Value(1, "Inactive")
val Active = Value(2, "Active")
val Deleted = Value(3, "Deleted")
implicit val myEnumFormat = new Format[Status] {
def reads(json: JsValue) = JsSuccess(Status.withName(json.as[String]))
def writes(myEnum: Status) = JsString(myEnum.toString)
}
}
示例13: EstadoPedido
//设置package包名称以及导入依赖的类
package domain
import play.api.libs.json.{Format, JsString, JsSuccess, JsValue}
object EstadoPedido extends Enumeration {
type EstadoPedido = Value
val Generado = Value(1, "Generado")
val Pendiente = Value(2, "Pendiente")
val Confeccionado = Value(3, "Confeccionado")
val Entregado = Value(4, "Entregado")
val Cancelado = Value(5, "Cancelado")
implicit val myEnumFormat = new Format[EstadoPedido] {
def reads(json: JsValue) = JsSuccess(EstadoPedido.withName(json.as[String]))
def writes(myEnum: EstadoPedido) = JsString(myEnum.toString)
}
}
示例14: Categoria
//设置package包名称以及导入依赖的类
package domain
import play.api.libs.json.{Format, JsString, JsSuccess, JsValue}
object Categoria extends Enumeration {
type Categoria = Value
val Entradas = Value(1, "Entradas")
val PlatosPrincipales = Value(2, "PlatosPrincipales")
val Postres = Value(3, "Postres")
val Bebidas = Value(4, "Bebidas")
val Cafeteria = Value(5, "Cafeteria")
implicit val myEnumFormat = new Format[Categoria] {
def reads(json: JsValue) = JsSuccess(Categoria.withName(json.as[String]))
def writes(myEnum: Categoria) = JsString(myEnum.toString)
}
}
示例15: processRegister
//设置package包名称以及导入依赖的类
package application.user.signup
import datastructures.Register
import play.api.libs.json.{JsValue, Json}
import services.cryptography.BCrypt
import services.time.TimeServices
trait RegisterServices {
def processRegister(r : Register) : Register
def makeResponse : JsValue
}
class UserRegister extends RegisterServices with BCrypt {
override def processRegister(reg : Register): Register = {
val register = Register(reg.username, createHash(reg.password), reg.email)
register
}
override def makeResponse : JsValue = {
Json.parse(s"""{ "status" : 200, "message" : "Successfully Registered"}""")
}
}