本文整理汇总了Scala中play.api.libs.json.JsString类的典型用法代码示例。如果您正苦于以下问题:Scala JsString类的具体用法?Scala JsString怎么用?Scala JsString使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了JsString类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: 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))
}
示例2: 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)
}
}
示例3: 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)
}
}
示例4: 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)
}
}
示例5: JsonRequestSpec
//设置package包名称以及导入依赖的类
package play.api.libs.ws.ahc
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.util.ByteString
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import org.specs2.specification.AfterAll
import play.api.libs.json.{ JsString, Json }
import play.api.libs.ws.JsonBodyWritables
import play.libs.ws.DefaultObjectMapper
class JsonRequestSpec extends Specification with Mockito with AfterAll with JsonBodyWritables {
sequential
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
override def afterAll: Unit = {
system.terminate()
}
"set a json node" in {
val jsValue = Json.obj("k1" -> JsString("v1"))
val client = mock[StandaloneAhcWSClient]
val req = new StandaloneAhcWSRequest(client, "http://playframework.com/", null)
.withBody(jsValue)
.asInstanceOf[StandaloneAhcWSRequest]
.buildRequest()
req.getHeaders.get("Content-Type") must be_==("application/json")
ByteString.fromArray(req.getByteData).utf8String must be_==("""{"k1":"v1"}""")
}
"set a json node using the default object mapper" in {
val objectMapper = DefaultObjectMapper.instance
implicit val jsonReadable = body(objectMapper)
val jsonNode = objectMapper.readTree("""{"k1":"v1"}""")
val client = mock[StandaloneAhcWSClient]
val req = new StandaloneAhcWSRequest(client, "http://playframework.com/", null)
.withBody(jsonNode)
.asInstanceOf[StandaloneAhcWSRequest]
.buildRequest()
req.getHeaders.get("Content-Type") must be_==("application/json")
ByteString.fromArray(req.getByteData).utf8String must be_==("""{"k1":"v1"}""")
}
}
示例6: JsonResultFormatSpec
//设置package包名称以及导入依赖的类
package com.pygmalios.reactiveinflux.command.query
import org.junit.runner.RunWith
import org.scalatest.FlatSpec
import org.scalatest.junit.JUnitRunner
import play.api.libs.json.{JsNumber, JsString, Json}
@RunWith(classOf[JUnitRunner])
class JsonResultFormatSpec extends FlatSpec {
import JsonResultFormatSpec._
import JsonResultFormat._
behavior of "format"
it should "parse result with one series" in {
// Execute
val jsonResult = Json.parse(example1).as[JsonResult]
assert(jsonResult.series.size == 1)
val series = jsonResult.series.head
assert(series.name == "cpu_load_short")
assert(series.columns == List("time", "value"))
assert(series.values.size == 3)
assert(series.values(0)(0) == JsString("2015-01-29T21:55:43.702900257Z"))
assert(series.values(0)(1) == JsNumber(0.55))
assert(series.values(1)(0) == JsString("2015-01-29T21:55:43.702900257Z"))
assert(series.values(1)(1) == JsNumber(23422))
assert(series.values(2)(0) == JsString("2015-06-11T20:46:02Z"))
assert(series.values(2)(1) == JsNumber(0.64))
}
}
object JsonResultFormatSpec {
val example1 = """
|{
| "series": [
| {
| "name": "cpu_load_short",
| "columns": [
| "time",
| "value"
| ],
| "values": [
| [
| "2015-01-29T21:55:43.702900257Z",
| 0.55
| ],
| [
| "2015-01-29T21:55:43.702900257Z",
| 23422
| ],
| [
| "2015-06-11T20:46:02Z",
| 0.64
| ]
| ]
| }
| ]
| }
""".stripMargin
}
示例7: writes
//设置package包名称以及导入依赖的类
package responses
import java.sql.Timestamp
import java.text.SimpleDateFormat
import play.api.libs.json.{Json, JsString, JsValue, Writes}
import models.{DriverModel, DriverLocationModel}
trait ResponseFormatter {
implicit val timestampWriter = new Writes[Timestamp] {
override def writes(t: Timestamp): JsValue = JsString(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(t))
}
implicit val driverResponse = Json.writes[DriverResponse]
implicit val seqDriverResponse = Json.writes[SeqDriverResponse]
def toDriverResponse(driver: DriverModel): DriverResponse = {
DriverResponse(
id = driver.id,
name = driver.name,
vehicle = driver.vehicle
)
}
def toDriverListResponse(seqDrv: Seq[DriverModel]): SeqDriverResponse = {
SeqDriverResponse(
drivers = seqDrv.map(toDriverResponse)
)
}
}
object ResponseFormatter extends ResponseFormatter
示例8: Register
//设置package包名称以及导入依赖的类
package io.orkestra.cluster
import akka.actor.ActorRef
import akka.http.scaladsl.model.{StatusCodes, StatusCode}
import play.api.libs.json.{JsString, Format, Json, JsValue}
package object protocol {
case class Register(member: ActorRef, role: String)
case class RegisterInternal(member: ActorRef, role: String)
sealed trait Response {
def asJson: JsValue
def httpStatusCode: StatusCode
}
object Response {
trait Success extends Response {
override val httpStatusCode: StatusCode = StatusCodes.OK
}
object Success {
case class Router(name: String, routees: List[String]) extends Success {
override val asJson = Json.toJson(this)
}
object Router {
implicit val fmt: Format[Router] = Json.format[Router]
}
case class Routers(routers: Iterable[JsValue]) extends Success {
override val asJson = Json.toJson(routers)
}
case class RouteeDeleted(role: String, path: String) extends Success {
override val asJson = JsString(s"routee: $path with role: $role successfully deleted")
}
}
trait Failure extends Response
object Failure {
case class RouterNotFound(role: String) extends Failure {
override val httpStatusCode: StatusCode = StatusCodes.NotFound
override val asJson: JsValue = Json.obj("error" -> s"router with role: $role not found")
}
}
}
}
示例9: 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))))
}
}
示例10: 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")
})
)))
}
示例11: ErrorHandler
//设置package包名称以及导入依赖的类
import javax.inject._
import play.api.http.DefaultHttpErrorHandler
import play.api._
import play.api.libs.json.JsString
import play.api.mvc._
import play.api.mvc.Results._
import play.api.routing.Router
import services.ApiSecurity
import scala.concurrent._
@Singleton
class ErrorHandler @Inject() (
env: Environment,
config: Configuration,
sourceMapper: OptionalSourceMapper,
router: Provider[Router]
) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) with ApiSecurity {
override def onBadRequest(request: RequestHeader, message: String): Future[Result] = {
Future.successful(
JsonAnswer(400,JsString("Bad Request Error: " + message))(request)
)
}
override def onServerError(request: RequestHeader, exception: Throwable): Future[Result] = {
Future.successful(
JsonAnswer(500,JsString("Internal Server Error: " + exception.getMessage))(request)
)
}
override def onNotFound(request: RequestHeader, message: String): Future[Result] = {
Future.successful(
JsonAnswer(404,JsString("Not Found Error: " + message))(request)
)
}
override def onForbidden(request: RequestHeader, message: String) = {
Future.successful(
Forbidden("You're not allowed to access this resource.")
)
}
}
示例12: ErrorHandler
//设置package包名称以及导入依赖的类
package ylabs.play.common
import java.io.{PrintWriter, StringWriter}
import javax.inject.{Inject, Provider}
import play.api.http.DefaultHttpErrorHandler
import play.api.libs.json.{JsObject, JsString, Json, Writes}
import play.api.mvc.RequestHeader
import play.api.mvc.Results._
import play.api.routing.Router
import play.api.{Configuration, Environment, OptionalSourceMapper, UsefulException}
import ylabs.play.common.models.Helpers.ApiFailure.Failed
import ylabs.play.common.models.ValidationError.{Field, Invalid, Reason}
import scala.concurrent.Future
class ErrorHandler @Inject() (
env: Environment,
config: Configuration,
sourceMapper: OptionalSourceMapper,
router: Provider[Router]) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {
def prettyTrace(t: Throwable) = {
val sw = new StringWriter
t.printStackTrace(new PrintWriter(sw))
sw.toString
}
implicit def exceptionWrites: Writes[Throwable] = new Writes[Throwable] {
def writes(t: Throwable) = JsObject(Seq(
"message" -> JsString(t.getMessage),
"trace" -> JsString(prettyTrace(t))))
}
override def onDevServerError(request: RequestHeader, exception: UsefulException) = {
Future.successful(InternalServerError(Json.toJson(exception)))
}
override def onProdServerError(request: RequestHeader, exception: UsefulException) = {
Future.successful(InternalServerError(Json.toJson("Internal Error")))
}
override def onBadRequest(request: RequestHeader, message: String) = {
def errorToMessage(error: String) = error match {
case "error.path.missing" ? "Value missing"
case _ ? error
}
//This is a bit of a mess because play doesn't allow invalid json to get to our client code
//Message will be something like "Json validation error List((obj.name,List(ValidationError(List(error.path.missing),WrappedArray()))))"
//So this extracts the field and reason
val errorRegex = """\(obj.([^,]+),List\(ValidationError\(List\(([^\)]+)""".r
val errors = errorRegex.findAllMatchIn(message) map { m ? Invalid(Field(m.group(1)), Reason(errorToMessage(m.group(2)))) }
val list = if(errors.nonEmpty) errors.toList else List(Invalid(Field("Unknown"), Reason(message)))
val failed = Failed(list)
Future.successful(BadRequest(Json.toJson(failed)))
}
}
示例13: JobCtrl
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import scala.annotation.implicitNotFound
import scala.concurrent.ExecutionContext
import scala.concurrent.duration.Duration
import scala.util.{ Failure, Success }
import play.api.libs.json.{ JsString, Json }
import play.api.mvc.{ Action, AnyContent, Controller }
import models.JsonFormat._
import services.JobSrv
class JobCtrl @Inject() (
jobSrv: JobSrv,
implicit val ec: ExecutionContext) extends Controller {
def list(dataTypeFilter: Option[String], dataFilter: Option[String], analyzerFilter: Option[String], start: Int, limit: Int): Action[AnyContent] = Action.async { request ?
jobSrv.list(dataTypeFilter, dataFilter, analyzerFilter, start, limit).map {
case (total, jobs) ? Ok(Json.toJson(jobs)).withHeaders("X-Total" ? total.toString)
}
}
def get(jobId: String): Action[AnyContent] = Action.async { request ?
jobSrv.get(jobId).map { job ?
Ok(Json.toJson(job))
}
}
def remove(jobId: String): Action[AnyContent] = Action.async { request ?
jobSrv.remove(jobId).map(_ ? Ok(""))
}
def report(jobId: String): Action[AnyContent] = Action.async { request ?
jobSrv
.get(jobId)
.map { job ?
val report = job.report.value match {
case Some(Success(r)) ? Json.toJson(r)
case Some(Failure(error)) ? JsString(error.getMessage)
case None ? JsString("Running")
}
Ok(jobWrites.writes(job) +
("status" ? jobStatusWrites.writes(job.status)) +
("report" ? report))
}
}
def waitReport(jobId: String, atMost: String): Action[AnyContent] = Action.async { request ?
jobSrv.waitReport(jobId, Duration(atMost))
.map { job ? Ok(Json.toJson(job)) }
}
}
示例14: singleValue
//设置package包名称以及导入依赖的类
package model.sensor
import play.api.libs.json.{JsString, JsValue, Writes}
def singleValue(value: Double): Double
}
object IdentityMeasurementAggregationStrategy extends MeasurementAggregationStrategy {
override def singleValue(value: Double): Double = value
}
object BooleanMeasurementAggregationStrategy extends MeasurementAggregationStrategy {
override def singleValue(value: Double): Double = if(value > 0) 10 else 0
}
object MeasurementAggregationStrategy {
implicit val writes: Writes[MeasurementAggregationStrategy] =
new Writes[MeasurementAggregationStrategy] {
def writes(o: MeasurementAggregationStrategy): JsValue = o match {
case IdentityMeasurementAggregationStrategy => JsString("none")
case BooleanMeasurementAggregationStrategy => JsString("boolean")
}
}
}
示例15: OrderDetails
//设置package包名称以及导入依赖的类
package model.read
import model.{ ItemId, OrderNumber }
import play.api.libs.json.{ JsString, JsValue, Json, Writes }
case class OrderDetails(number: OrderNumber, status: OrderStatus, items: List[ItemDetails] = List.empty) {
lazy val totalAmount = items.map(_.price).sum
}
case class ItemDetails(itemId: ItemId, name: String, price: Double)
object ItemDetails {
implicit val writes = Json.writes[ItemDetails]
}
sealed trait OrderStatus
case object Initiated extends OrderStatus
case object Open extends OrderStatus
case object Payed extends OrderStatus
case object Cancelled extends OrderStatus
object OrderStatus {
implicit val writes = new Writes[OrderStatus] {
def writes(o: OrderStatus): JsValue = {
o match {
case Initiated => JsString("initiated")
case Open => JsString("open")
case Payed => JsString("payed")
case Cancelled => JsString("cancelled")
}
}
}
}
object OrderDetails {
val writesCaseClass = Json.writes[OrderDetails]
implicit val writes = new Writes[OrderDetails] {
def writes(o: OrderDetails): JsValue = {
Json.obj("total" -> o.totalAmount) ++ writesCaseClass.writes(o)
}
}
}