本文整理汇总了Scala中play.api.libs.json.JsNull类的典型用法代码示例。如果您正苦于以下问题:Scala JsNull类的具体用法?Scala JsNull怎么用?Scala JsNull使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了JsNull类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: ErrorResult
//设置package包名称以及导入依赖的类
package controllers.responses
import play.api.libs.json.{Json, Format, Writes}
import play.api.libs.json.{JsValue, JsNull}
case class ErrorResult(status: Int,message: String)
object ErrorResult {
implicit val format: Format[ErrorResult]
= Json.format[ErrorResult]
}
case class EndpointResponse(
result: String,
response: JsValue,
error: Option[ErrorResult])
object EndpointResponse {
implicit val format: Format[EndpointResponse]
= Json.format[EndpointResponse]
}
object ErrorResponse {
def apply(status: Int, message: String) = {
EndpointResponse("ko", JsNull, Option(ErrorResult(status, message)))
}
def INVALID_JSON = 1000
}
object SuccessResponse {
def apply[A](successResponse: A)(implicit w: Writes[A]) = {
EndpointResponse("ok", Json.toJson(successResponse), None)
}
}
示例2: EventVersionSpec
//设置package包名称以及导入依赖的类
package eventsource.models
import org.scalatest.{MustMatchers, WordSpec}
import play.api.libs.json.{JsNull, Json}
class EventVersionSpec extends WordSpec with MustMatchers {
"EventVersion" should {
"order by offset in the same partition" in {
val version1 = EventVersion(1, 100)
val version2 = EventVersion(1, 101)
version2.isNewerThan(version1) mustBe true
version1.isNewerThan(version2) mustBe false
}
"handle a re-partitioning" in {
val version1 = EventVersion(1, 100)
val version2 = EventVersion(2, 1)
version2.isNewerThan(version1) mustBe true
version1.isNewerThan(version2) mustBe true
}
"deserialize to unknonw if not present in json" in {
val json = Json.obj(
"id" -> "id",
"anInt" -> 1,
"aString" -> "string",
"createdVersion" -> Json.obj(
"partition" -> 2,
"offset" -> 123
),
"lastModifiedVersion" -> JsNull
)
val someEntity = json.as[SomeEntity]
someEntity.createdVersion mustBe EventVersion(2, 123)
someEntity.lastModifiedVersion mustBe EventVersion.undefined
}
}
}
示例3: Application
//设置package包名称以及导入依赖的类
package controllers
import play.api._
import play.api.mvc._
import play.api.libs.json.{JsNull,Json,JsString,JsValue}
class Application extends Controller {
def index = Action {
Ok(views.html.index())
}
def json = Action {
val json: JsValue = Json.obj(
"name" -> "Watership Down",
"location" -> Json.obj("lat" -> 51.235685, "long" -> -1.309197),
"residents" -> Json.arr(
Json.obj(
"name" -> "Fiver",
"age" -> 4,
"role" -> JsNull
),
Json.obj(
"name" -> "Bigwig",
"age" -> 6,
"role" -> "Owsla"
)
)
)
Ok(json)
}
}
示例4: ErrorResult
//设置package包名称以及导入依赖的类
package controllers.responses
import play.api.libs.json.{ Json, Format, JsValue, JsNull, Writes }
case class ErrorResult(status: Int, message: String)
object ErrorResult {
implicit val format: Format[ErrorResult] = Json.format[ErrorResult]
}
case class EndpointResponse(
result: String,
response: JsValue,
error: Option[ErrorResult])
object EndpointResponse {
implicit val format: Format[EndpointResponse] = Json.format[EndpointResponse]
}
object ErrorResponse {
val INVALID_JSON = 1000
def apply(status: Int, message: String) = {
EndpointResponse("ko", JsNull, Option(ErrorResult(status, message)))
}
}
object SuccessResponse {
def apply[A](successResponse: A)(implicit w: Writes[A]) = {
EndpointResponse("ok", Json.toJson(successResponse), None)
}
}
示例5: coproductWrites
//设置package包名称以及导入依赖的类
package microtools.shapeless
import play.api.data.validation.ValidationError
import play.api.libs.json.{JsError, JsNull, Reads, Writes}
import shapeless.{:+:, CNil, Coproduct, Inl, Inr, Lazy}
trait ShapelessCoproductJson {
implicit val cNilWrites: Writes[CNil] = Writes[CNil](_ => JsNull)
implicit val cNilReads: Reads[CNil] = Reads[CNil](_ => JsError(ValidationError("error.invalid")))
implicit def coproductWrites[H, T <: Coproduct](
implicit hWrites: Lazy[Writes[H]],
tWrites: Writes[T]
): Writes[H :+: T] = Writes[H :+: T] {
case Inl(h) => hWrites.value.writes(h)
case Inr(t) => tWrites.writes(t)
}
implicit def coproductReads[H, T <: Coproduct](implicit hReads: Lazy[Reads[H]],
tReads: Reads[T]): Reads[H :+: T] =
hReads.value.map[H :+: T](h => Inl[H, T](h)) orElse tReads.map[H :+: T](t => Inr[H, T](t))
}
object ShapelessCoproductJson extends ShapelessCoproductJson
示例6: ShapelessListJsonSpec
//设置package包名称以及导入依赖的类
package microtools.shapeless
import org.scalatest.MustMatchers
import org.scalatestplus.play.PlaySpec
import play.api.libs.json.{JsNull, Json}
import shapeless.HNil
class ShapelessListJsonSpec extends PlaySpec with MustMatchers {
import ShapelessListJson._
"Shapeless writes" should {
"serialize HNil to null" in {
val json = Json.toJson(HNil)
json mustBe JsNull
}
"serialize generic HList to array" in {
val json =
Json.toJson(1234 :: "string" :: true :: HNil)
(json \ 0).as[Int] mustBe 1234
(json \ 1).as[String] mustBe "string"
(json \ 2).as[Boolean] mustBe true
Json.toJson(1234 :: "string" :: true :: HNil)
}
}
}
示例7: json
//设置package包名称以及导入依赖的类
package com.wavesplatform.matcher.api
import akka.http.scaladsl.model.{StatusCode, StatusCodes}
import play.api.libs.json.{JsNull, JsValue, Json}
trait MatcherResponse {
def json: JsValue
def code: StatusCode
}
trait GenericMatcherResponse extends MatcherResponse {
def success: Boolean
def message: String
def result: JsValue = JsNull
def json: JsValue = Json.obj(
"success" -> success,
"message" -> message,
"result" -> result
)
def code: StatusCode = if (success) StatusCodes.OK else StatusCodes.BadRequest
}
case class StatusCodeMatcherResponse(override val code: StatusCode, message: String) extends GenericMatcherResponse {
override def success: Boolean = code == StatusCodes.OK
}
case class BadMatcherResponse(override val code: StatusCode, message: String) extends GenericMatcherResponse {
override def success: Boolean = code == StatusCodes.OK
}
示例8: ErrorResult
//设置package包名称以及导入依赖的类
package controllers.responses
import play.api.libs.json.{Json, Format, JsValue, JsNull, Writes}
case class ErrorResult (
status: Int,
message: String
)
object ErrorResult {
implicit val format: Format[ErrorResult] = Json.format[ErrorResult]
}
case class APIResponse (
result: String,
response: JsValue,
error: Option[ErrorResult]
)
object APIResponse {
implicit val format: Format[APIResponse] = Json.format[APIResponse]
}
object ErrorResponse {
val INVALID_JSON = 1000
val NOT_ENOUGH_TICKETS = 1001
def apply(status: Int, message: String) = {
APIResponse("ko", JsNull, Option(ErrorResult(status, message)))
}
}
object SuccessResponse {
def apply[A](successResponse: A)(implicit w: Writes[A]) = {
APIResponse("ok", Json.toJson(successResponse), None)
}
}
示例9: ChatWorkApiResponse
//设置package包名称以及导入依赖的类
package tv.kazu.chatwork4s
import play.api.libs.json.{JsNull, Reads, Json, JsValue}
import tv.kazu.chatwork4s.models._
import scalaj.http.HttpResponse
class ChatWorkApiResponse(val httpResponse: HttpResponse[String]) {
val body = if (!httpResponse.body.isEmpty) Some(httpResponse.body) else None
val jsValue: JsValue = body map { bodyStr =>
Json.parse(bodyStr)
} getOrElse {
JsNull
}
def as[T](implicit reads: Reads[T]): T = {
jsValue.as[T]
}
def asEither[T](implicit reads: Reads[T]): Either[List[String], T] = {
if (httpResponse.isSuccess) {
Right(jsValue.as[T])
} else {
Left((jsValue \ "errors").get.as[List[String]])
}
}
}
object ChatWorkApiResponse {
object Implicits {
import com.github.tototoshi.play.json.JsonNaming
implicit val userReads: Reads[User] = JsonNaming.snakecase(Json.reads[User])
implicit val userMiniReads: Reads[UserMini] = JsonNaming.snakecase(Json.reads[UserMini])
implicit val userFullReads: Reads[UserFull] = JsonNaming.snakecase(Json.reads[UserFull])
implicit val roomReads: Reads[Room] = JsonNaming.snakecase(Json.reads[Room])
implicit val messageReads: Reads[Message] = JsonNaming.snakecase(Json.reads[Message])
}
}
示例10: MapReader
//设置package包名称以及导入依赖的类
package utilities
import play.api.libs.json.{JsNull, JsObject, JsValue, Json}
class MapReader {
def mapToJson(x: Any): JsValue = {
x match {
case j: JsValue => x.asInstanceOf[JsValue]
case m: Map[String, Any] => Json.toJson(JsObject(x.asInstanceOf[Map[String, Any]].map(y => (y._1 -> mapToJson(y._2)))))
case l: List[Any] => Json.toJson(x.asInstanceOf[List[Any]].map(y => mapToJson(y)))
case s: String => Json.toJson(x.asInstanceOf[String])
case b: Boolean => Json.toJson(x.asInstanceOf[Boolean])
case i: Int => Json.toJson(x.asInstanceOf[Int])
case lo: Long => Json.toJson(x.asInstanceOf[Long])
case d: Double => Json.toJson(x.asInstanceOf[Double])
case List() => Json.toJson(JsNull)
case seq: List[List[Any]] => Json.toJson(x.asInstanceOf[List[List[Any]]].map(y => mapToJson(y)))
// case null => Json.toJson(JsNull)
case _ => Json.toJson(x.toString())
}}
def mapToJson(m: Map[String,Any]): JsValue = {
mapToJson(m.asInstanceOf[Any])
}
def mapToJsString(m:Map[String, Any]): String = {
mapToJson(m.asInstanceOf[Any]).toString
}
}
示例11: FieldExtractor
//设置package包名称以及导入依赖的类
package controllers
import java.util.{Date, UUID}
import models.adverts.{Fields, Fuel}
import play.api.libs.json.{JsDefined, JsNull, JsValue}
// TODO: Do not use "get" it's not safe
object FieldExtractor {
def getUUID(json: JsValue) = {
(json \ Fields.id).get.as[UUID]
}
def getTitle(json: JsValue) = {
(json \ Fields.title).get.as[String]
}
def getPrice(json: JsValue) = {
(json \ Fields.price).get.as[Int]
}
def getIsNew(json: JsValue) = {
(json \ Fields.isNew).get.as[Boolean]
}
def getFuel(json: JsValue) = {
val name = (json \ Fields.fuel).getOrElse(JsNull).as[String]
Fuel.findByName(name)
}
def getMileage(json: JsValue): Option[Int] = {
json \ Fields.mileage match {
case JsDefined(value) => Some(value.as[Int])
case _ => None
}
}
def getFirstRegistration(json: JsValue): Option[Date] = {
json \ Fields.firstRegistration match {
case JsDefined(value) => Some(value.as[Date])
case _ => None
}
}
}
示例12: index
//设置package包名称以及导入依赖的类
package controllers
import javax.inject._
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.json.JsNull
import play.api.mvc._
import services.Constants.{failMessage, succMessage}
import services.{CapchaVerifyService, MailerService}
import scala.concurrent.Future
import scala.util.{Failure, Success}
def index(capchaCode: String, name: String, email: String, subject: String, message: String): Action[AnyContent] = Action.async {
capchaVerifyService.verify(capchaCode).map { verified =>
if (verified) {
val result: Future[Boolean] = mailerService.sendMail(name, email, subject, message)
result.map(value => {
if (value) Ok(succMessage(JsNull)) else BadRequest(failMessage("Did not successfully send message"))
})
} else {
Future {
BadRequest(failMessage("Failed to verify recapcha token"))
}
}
}.flatMap(identity) recover {
case _ => BadRequest(failMessage("Failed to verify recapcha token"))
}
}
}
示例13: ApiLogService
//设置package包名称以及导入依赖的类
package domain.service
import javax.inject.Inject
import api.ApiRequestHeader
import api.ApiUtil._
import ApiToken._
import domain.models.Tables
import play.api.cache.CacheApi
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfig}
import play.api.libs.json.{JsNull, JsValue, Json}
import play.api.mvc.RequestHeader
import slick.driver.JdbcProfile
class ApiLogService @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends Tables with HasDatabaseConfig[JdbcProfile] {
val dbConfig = dbConfigProvider.get[JdbcProfile]
val profile = slick.driver.MySQLDriver
import dbConfig.driver.api._
def insert[R <: RequestHeader](status: Int, json: JsValue)(implicit cache: CacheApi,request: ApiRequestHeader[R]) = {
val row = ApilogRow(
datetime = currentTimestamp,
ip = request.remoteAddress,
token = request.maybeAuthToken,
method = request.method,
uri = request.uri,
requestbody = request.maybeBody,
responsestatus = status,
responsebody = if (json == JsNull) None else Some(Json.prettyPrint(json)),
email = getMaybeEmail(request.maybeAuthToken)
)
def token(implicit request: ApiRequestHeader[R]): String = {
request.maybeAuthToken match {
case Some(t) => t
case None => EMPTY_STRING
}
}
db.run(Apilog += row)
}
}
示例14: CustomRouter
//设置package包名称以及导入依赖的类
package api
import javax.inject.{Inject, Named}
import akka.actor.ActorRef
import com.viajobien.busy.actors.ProducerActor
import play.api.Logger
import play.api.libs.json.{JsNull, Json}
import play.api.mvc.Action
import play.api.mvc.Results._
import play.api.routing.Router.Routes
import play.api.routing.SimpleRouter
import repositories.RouteRepository
import services.RouteService
import scala.concurrent.{ExecutionContext, Future}
class CustomRouter @Inject()(@Named(ProducerActor.name) producerActor: ActorRef,
routeService: RouteService, routeRepository: RouteRepository
)(implicit ec: ExecutionContext) extends SimpleRouter {
override def routes: Routes = {
case _ =>
Action.async { implicit request =>
val future = this.routeService.route(
futureJson => futureJson map {
case JsNull => ServiceUnavailable(Json.obj("error" -> "Error on access service"))
case json => Ok(json)
},
() => Future.successful(BadGateway(Json.obj("error" -> "route not found")))
)
future recover {
case e =>
Logger.warn("error on getRoute", e)
ServiceUnavailable(Json.obj("error" -> "error calling route"))
}
}
}
}
示例15: JsonTools
//设置package包名称以及导入依赖的类
package com.seancheatham.graph.utility
import play.api.libs.json.{JsNull, JsObject, JsValue}
object JsonTools {
implicit class JsObjectHelper(obj: JsObject) {
def withoutNulls: JsObject =
JsObject(obj.value collect {
case (key, obj1: JsObject) =>
key -> obj1.withoutNulls
case (key, value) if value != JsNull =>
key -> value
}
)
}
implicit class JsonMapHelper(map: Map[String, JsValue]) {
def withoutNulls =
map collect {
case (key, obj1: JsObject) =>
key -> obj1.withoutNulls
case (key, value) if value != JsNull =>
key -> value
}
}
}