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

Scala JsValue类代码示例

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

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



在下文中一共展示了JsValue类的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: 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))
} 
开发者ID:OCervantes,项目名称:websocket-play,代码行数:33,代码来源:UserActor.scala


示例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)
} 
开发者ID:commodityvectors,项目名称:scalatest-snapshot-matchers,代码行数:27,代码来源:PlayJsonSnapshotMatcher.scala


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


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


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


示例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())
  }
} 
开发者ID:laurinka,项目名称:golfmit,代码行数:42,代码来源:OpenIdInfoQueries.scala


示例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
  }
} 
开发者ID:GalacticFog,项目名称:gestalt-lambda,代码行数:20,代码来源:Utility.scala


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

} 
开发者ID:Sengab-platform,项目名称:backend,代码行数:31,代码来源:TemplateBody.scala


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


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

  }

} 
开发者ID:AppMinistry,项目名称:scathon,代码行数:32,代码来源:MiscEndpointTests.scala


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


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


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


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


示例16: createPost

//设置package包名称以及导入依赖的类
package application.user.post

import datastructures.{Comment, Post, UserPost}
import play.api.libs.json.{JsValue, Json}
import services.cryptography.{JwtTokenGenerator, JwtTokenGeneratorServices}
import services.time.TimeServices


trait UserPostServices {
  def createPost(p : datastructures.UserPost) : datastructures.UserPost
  def getPost(id : String) : Array[Post]
  def makeJsonPost(p : Post) : JsValue
  def makeJson() : JsValue
}

class UserPost extends UserPostServices {

  val jwtTokenServices : JwtTokenGeneratorServices = new JwtTokenGenerator

  override def createPost(p: datastructures.UserPost): datastructures.UserPost = {
    val initComments = Array[Comment]()
    val timeOfCreation = TimeServices.createTime

    val post = datastructures.UserPost(
      userid = jwtTokenServices.fetchPayload(""),
      time = timeOfCreation,
      description = p.description,
      postPictures = p.postPictures
    )
    post
  }

  override def makeJsonPost(p: Post): JsValue = ???

  override def makeJson : JsValue = Json.parse(s"""{ "status" : 200, "message" : "successful" }""")

  override def getPost(id: String): Array[Post] = ???
} 
开发者ID:mubeenahmed,项目名称:MeGuideApi,代码行数:39,代码来源:PostServices.scala


示例17: Actions

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

import play.api.libs.json.JsValue
import play.api.mvc.Request

import users.{Validator => UserValidator}
import users.RequestSerializer.deserialize

import scala.concurrent.Future
import scala.concurrent.ExecutionContext

object Actions {
  def create(request: Request[JsValue])(implicit ec: ExecutionContext) = {
    val record = request.body.as[User](deserialize)

    UserValidator.validate(record) map { validator =>
      if (validator) {
        Users.create(record)
        val userFromDB = Users.findByEmail(record.email).map(_.get)

        (userFromDB, true)
      } else (Future.successful(record), false)
    }
  }
} 
开发者ID:dsounded,项目名称:money_exchanger,代码行数:26,代码来源:Actions.scala


示例18: PersonController

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

import javax.inject._

import model.Person
import play.api.Logger
import play.api.libs.json.{JsArray, JsValue, Json, Writes}
import play.api.mvc._

@Singleton
class PersonController @Inject() extends Controller {
  val logger = Logger(this.getClass)

  implicit val personWrites = new Writes[Person] {
    override def writes(person: Person): JsValue = Json.obj(
      "id" -> person.id,
      "name" -> person.name
    )
  }

  def all = Action {
    logger.debug(s"GET all: ${PersonController.persons.size}")
    val result = PersonController.persons.values.map(p => Json.toJson(p)).toSeq
    Ok(Json.toJson(JsArray(result)))
  }

  def put() = Action { request =>
    val jsonBody = request.body.asJson

    jsonBody.map { json =>
      logger.debug(s"PUT json is $json")
      jsonToPerson(json).map { person =>
        logger.debug(s"Inserting a $person")
        PersonController.persons += person.id -> person
        NoContent
      }.getOrElse {
        BadRequest("Missing data fields")
      }
      NoContent
    }.getOrElse {
      BadRequest("Expecting json in request body")
    }
  }

  private def jsonToPerson(json: JsValue): Option[Person] = {
    val id = (json \ "id").as[Int]
    val name = (json \ "name").as[String]

    if (id != 0 && name != null) {
      Some(Person(id, name))
    } else {
      None
    }
  }
}

object PersonController {
  var persons = Map.empty[Int, Person]
} 
开发者ID:jonasrichard,项目名称:chat-play,代码行数:60,代码来源:PersonController.scala


示例19: toJson

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

import java.util.Date

import play.api.libs.json.{JsValue, Json}



trait JsonTodo{
  protected val format = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
  def toJson: JsValue
}

case class Todo(id: String, description: String, date : Date) extends JsonTodo{

  override def toJson : JsValue = {
    Json.obj(
      "id" -> this.id,
      "description" -> this.description,
      "date" -> format.format(this.date)
    )
  }
}

case class TodoHistory(id: String, description: String, itemId: String, itemDescription: Option[String], date : Date) extends JsonTodo{

  override def toJson : JsValue = {
    val json = Json.obj(
      "id" -> this.id,
      "description" -> this.description,
      "itemId" -> this.itemId,
      "date" -> format.format(this.date)
    )

    this.itemDescription.map(item => json.++(Json.obj("itemDescription" -> item))).getOrElse(json)
  }
} 
开发者ID:mrolnik,项目名称:to-do-list-app,代码行数:38,代码来源:Todos.scala


示例20: Event

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

import play.api.libs.json.{JsValue, Json}



abstract class Event()

case class EventA(data: String, eventType: String = "a") extends Event

case class EventB(data: String, eventType: String = "b") extends Event

object EventA {
  implicit val format = Json.format[EventA]
}

object EventB {
  implicit val format = Json.format[EventB]
}

object Event {
  implicit def json2object(value: JsValue): Event = {
    (value \ "eventType").as[String] match {
      case "a" => value.as[EventA]
      case "b" => value.as[EventB]
    }
  }

  implicit def object2json(event: Event): JsValue = {
    event match {
      case event: EventA => Json.toJson(event)
      case event: EventB => Json.toJson(event)
    }
  }
} 
开发者ID:koduki,项目名称:example-palyframework,代码行数:36,代码来源:Events.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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