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

Scala JsString类代码示例

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

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



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


示例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)
  }
} 
开发者ID:dtambussi,项目名称:pedidos,代码行数:17,代码来源:Status.scala


示例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)
  }
} 
开发者ID:dtambussi,项目名称:pedidos,代码行数:19,代码来源:EstadoPedido.scala


示例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)
  }
} 
开发者ID:dtambussi,项目名称:pedidos,代码行数:19,代码来源:Categoria.scala


示例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"}""")
  }
} 
开发者ID:playframework,项目名称:play-ws,代码行数:51,代码来源:JsonRequestSpec.scala


示例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
} 
开发者ID:pygmalios,项目名称:reactiveinflux,代码行数:62,代码来源:JsonResultFormatSpec.scala


示例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 Writes1653288512 {
    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 
开发者ID:astahiam,项目名称:drivers,代码行数:34,代码来源:ResponseFormatter.scala


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

} 
开发者ID:cognitev,项目名称:akka-cluster-manager,代码行数:53,代码来源:package.scala


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

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


示例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")
      })
    )))
} 
开发者ID:kuhnuri,项目名称:kuhnuri-worker,代码行数:20,代码来源:ConversionStatus.scala


示例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.")
    )
  }
} 
开发者ID:kormoglaz,项目名称:TestTask,代码行数:45,代码来源:ErrorHandler.scala


示例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)))
  }
} 
开发者ID:springnz,项目名称:play-app-base,代码行数:60,代码来源:ErrorHandler.scala


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


示例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")
      }
    }
} 
开发者ID:vavravl1,项目名称:home_center,代码行数:26,代码来源:MeasurementAggregationStrategy.scala


示例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)
    }
  }
} 
开发者ID:strongtyped,项目名称:fun-cqrs-order-demo,代码行数:45,代码来源:OrderDetails.scala


示例16: aultErrorHandler

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

import play.api.data.validation.ValidationError
import play.api.libs.json.{JsError, JsObject, JsPath, JsString}
import play.api.mvc.Controller


trait ControllerSupport extends Controller{
  protected val defaultErrorHandler = {
    error: Seq[(JsPath, Seq[ValidationError])] =>
      BadRequestForValidate(JsError.toFlatJson(error))
  }
  protected val BadRequestForValidate = {
    param: JsObject => BadRequest(createErrorResponse(s"Validate Error: $param"))
  }

  protected def createErrorResponse(message: String) = JsObject(
    Seq(
      "message" -> JsString(message)
    )
  )

} 
开发者ID:teruuuuuu,项目名称:todo_server_scala,代码行数:24,代码来源:ControllerSupport.scala


示例17: EventStreamActor

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

import java.util.UUID

import akka.actor.Actor.Receive
import akka.actor.Props
import akka.stream.actor.ActorPublisher
import play.api.libs.json.{JsObject, JsString, JsValue}



class EventStreamActor extends ActorPublisher[JsValue] {
  import EventStreamActor._
  import akka.stream.actor.ActorPublisherMessage._
  
  override def receive: Receive = {
    case DataUpdated(js) => onNext(js)
    case ErrorOccurred(msg) => onNext(JsObject(Seq("error" -> JsString(msg))))
    case Request(_) => ()
    case Cancel => context.stop(self)
  }
}

object EventStreamActor {
  def props = Props(new EventStreamActor)
  
  case class DataUpdated(jsValue: JsValue)
  case class ErrorOccurred(message: String)
  
  val name = "event-stream-actor"
  val pathPattern = s"/user/$name-*"
  
  def name(maybeUserId: Option[UUID]): String = {
    val randomPart = UUID.randomUUID().toString.split("-").apply(0)
    val userPart = maybeUserId.map(_.toString).getOrElse("unregistered")
    s"$name-$userPart-$randomPart"
  }
  
  def userSpecificPathPattern(userId: UUID): String = {
    s"/user/$name-${userId.toString}-*"
  }
} 
开发者ID:getArtemUsername,项目名称:play-and-events,代码行数:43,代码来源:EventStreamActor.scala


示例18: asResult

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

import microtools.logging.{LoggingContext, WithContextAwareLogger}
import play.api.libs.json.{JsString, JsValue, Json}
import play.api.mvc.{Result, Results}


  def asResult(implicit loggingContext: LoggingContext): Result = {
    val detailsMessage = details.map(Json.stringify).getOrElse("")
    Problem.log.info(
      s"Returning business problem as result. [ code=$code, type=${`type`}, message=$message, details=$detailsMessage ]"
    )
    Results.Status(code)(Json.toJson(this)(Problem.jsonFormat))
  }

  def withDetails(details: String): Problem =
    withDetails(JsString(details))

  def withDetails(details: JsValue): Problem =
    this.copy(details = Some(details))
}

object Problem extends WithContextAwareLogger {
  implicit val jsonFormat = Json.format[Problem]

  def forStatus(code: Int, message: String): Problem = Problem(
    code = code,
    `type` = s"https://status.es/$code",
    message = message,
    details = None
  )
} 
开发者ID:21re,项目名称:play-micro-tools,代码行数:33,代码来源:Problem.scala


示例19: ShapelessCoproductJsonSpec

//设置package包名称以及导入依赖的类
package microtools.shapeless

import org.scalatest.MustMatchers
import org.scalatestplus.play.PlaySpec
import play.api.libs.json.{JsBoolean, JsNumber, JsString, Json}
import shapeless._

class ShapelessCoproductJsonSpec extends PlaySpec with MustMatchers {
  import ShapelessCoproductJson._

  "Shapeless writes" should {
    "serialize a simple coproduct" in {
      type ISB = Int :+: String :+: Boolean :+: CNil

      val isb1 = Coproduct[ISB](1234)
      val isb2 = Coproduct[ISB]("string")
      val isb3 = Coproduct[ISB](true)

      Json.toJson(isb1) mustBe JsNumber(1234)
      Json.toJson(isb2) mustBe JsString("string")
      Json.toJson(isb3) mustBe JsBoolean(true)
    }
  }

  "Shapeless reads" should {
    "deserialize a simple coproduct" in {
      type ISB = Int :+: String :+: Boolean :+: CNil

      val isb1 = JsBoolean(true).as[ISB]
      val isb2 = JsString("string").as[ISB]
      val isb3 = JsNumber(1234).as[ISB]

      isb1.select[Boolean] mustBe Some(true)
      isb2.select[String] mustBe Some("string")
      isb3.select[Int] mustBe Some(1234)
    }
  }
} 
开发者ID:21re,项目名称:play-micro-tools,代码行数:39,代码来源:ShapelessCoproductJsonSpec.scala


示例20: JsonPointerSpec

//设置package包名称以及导入依赖的类
package microtools.patch

import microtools.patch.JsonPointer._
import org.scalatest.{MustMatchers, WordSpec}
import play.api.libs.json.{JsPath, JsString, Json}

class JsonPointerSpec extends WordSpec with MustMatchers {
  "JsonPointer" should {
    "parser empty" in {
      JsString("").as[JsPath] mustBe JsPath
    }

    "parse simple path" in {
      JsString("/a/b/c").as[JsPath] mustBe (JsPath \ "a" \ "b" \ "c")
    }

    "unescape slash and tilde" in {
      JsString("/demo~10/t~0lde").as[JsPath] mustBe (JsPath \ "demo/0" \ "t~lde")
    }

    "Support array index" in {
      JsString("/demo/12").as[JsPath] mustBe (JsPath \ "demo" \ 12)
    }

    "write empty" in {
      Json.toJson(JsPath) mustBe JsString("")
    }

    "write simple path" in {
      Json.toJson(JsPath \ "a" \ "b" \ "c") mustBe JsString("/a/b/c")
    }

    "write array index" in {
      Json.toJson(JsPath \ "demo" \ 12) mustBe JsString("/demo/12")
    }

    "write escape symbols" in {
      Json.toJson(JsPath \ "~demo~" \ "/demo") mustBe JsString("/~0demo~0/~1demo")
    }
  }
} 
开发者ID:21re,项目名称:play-micro-tools,代码行数:42,代码来源:JsonPointerSpec.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala JsError类代码示例发布时间:2022-05-23
下一篇:
Scala PoisonPill类代码示例发布时间: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