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

Scala Writes类代码示例

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

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



在下文中一共展示了Writes类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: add

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

import com.google.inject.{ImplementedBy, Inject}
import model.{Artist, ArtistDAO, Temp}
import play.api.libs.json.{JsValue, Json, Writes}
import play.api.Logger

import scala.concurrent.ExecutionContext

@ImplementedBy(classOf[ArtistServicesImpl])
trait ArtistServices {
  def add (discActor : Artist) : Boolean
  def findAllByType(value: String)  : ArtistResponse
}

case class ArtistResponse(artists : List[Artist])

object ArtistResponse {

  //implicit val formatter1 = Json.format[Artist]
  implicit val formatter2 = Json.format[ArtistResponse]
  Logger.debug("Attempting risky calculation.")
  implicit val implicitFooWrites = new Writes[ArtistResponse] {
    def writes(discActors : ArtistResponse): JsValue = {
      Json.obj(
        "artists" -> discActors.artists
      )
    }
  }
}

class ArtistServicesImpl @Inject()(dao: ArtistDAO )(implicit ec: ExecutionContext) extends ArtistServices  {

  override def add(artist : Artist ): Boolean = {
    if(dao.addNew(artist)!=null)
       true
    else
      false
  }

  override def findAllByType(value: String): ArtistResponse = {
    println("Find Artist by Name: " + value)
    ArtistResponse(dao.getAllByName(value).filter(a => a.isDefined).map(a => a.get))
  }

} 
开发者ID:ralekar,项目名称:play-scala-casbah,代码行数:47,代码来源:ArtistServices.scala


示例2: WSGitHubAuthor

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

import play.api.libs.functional.syntax._
import play.api.libs.json.{JsPath, Json, Reads, Writes}

case class WSGitHubAuthor(login: String, avatarUrl: String)

object WSGitHubAuthor {
  implicit val gitHubAuthorReads: Reads[WSGitHubAuthor] = (
    (JsPath \ "login").read[String] and
      (JsPath \ "avatar_url").read[String]
    )(WSGitHubAuthor.apply _)

  implicit val gitHubAuthorWriters = new Writes[WSGitHubAuthor] {
    def writes(gitHubAuthor: WSGitHubAuthor) = Json.obj(
      "login"        -> gitHubAuthor.login,
      "avatar_url"    -> gitHubAuthor.avatarUrl
    )
  }
}

case class WSGitHubContributor(totalCommits: Int, author: WSGitHubAuthor)

object WSGitHubContributor {
  implicit val gitHubContributorReads: Reads[WSGitHubContributor] = (
    (JsPath \ "total").read[Int] and
      (JsPath \ "author").read[WSGitHubAuthor]
    )(WSGitHubContributor.apply _)

  implicit val gitHubContributorWriters = new Writes[WSGitHubContributor] {
    def writes(gitHubContributor: WSGitHubContributor) = Json.obj(
      "totalCommits"        -> gitHubContributor.totalCommits,
      "author"              -> gitHubContributor.author
    )
  }
} 
开发者ID:helde,项目名称:GitHubRepositoriesActivities,代码行数:37,代码来源:WSGitHubContributor.scala


示例3: WSGitHubCommit

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

import java.text.SimpleDateFormat
import java.util.Date

import play.api.libs.functional.syntax._
import play.api.libs.json.{JsPath, Json, Reads, Writes}

case class WSGitHubCommit(committer: String, date: Date) {
  def getFormatedDate: String = {
    val dateFormat: SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd")
    dateFormat.format(date)
  }
}

object WSGitHubCommit {
  implicit val gitHubProjectSummaryReads: Reads[WSGitHubCommit] = (
    (JsPath \ "email").read[String] and
      (JsPath \ "date").read[Date]
    )(WSGitHubCommit.apply _)

  implicit val gitHubProjectSummaryWriters = new Writes[WSGitHubCommit] {
    def writes(gitHubProjectSummary: WSGitHubCommit) = Json.obj(
      "email"        -> gitHubProjectSummary.committer,
      "date"         -> gitHubProjectSummary.date
    )
  }
} 
开发者ID:helde,项目名称:GitHubRepositoriesActivities,代码行数:29,代码来源:WSGitHubCommit.scala


示例4: In

//设置package包名称以及导入依赖的类
package akka.http.documenteddsl.directives

import akka.http.documenteddsl.PreprocessedFromEntityUnmarshaller
import akka.http.documenteddsl.documentation.RouteDocumentation
import akka.http.scaladsl.server.Directive1
import akka.http.scaladsl.unmarshalling._
import org.coursera.autoschema.AutoSchema
import play.api.libs.json.{Reads, Writes}

import scala.reflect.runtime.{universe => ru}

trait MarshallingDDirectives {

  final class In[T](example: Option[T] = None)(implicit um: PreprocessedFromEntityUnmarshaller[T], ev: ru.TypeTag[T], writes: Writes[T], reads: Reads[T]) extends DDirective1[T] {
    import akka.http.scaladsl.server.directives.MarshallingDirectives._
    import um.fsu
    def describe(w: RouteDocumentation)(implicit as: AutoSchema): RouteDocumentation = w.in[T](example map writes.writes)
    def delegate: Directive1[T] = entity(as[T])
  }

  object In {
    def apply[T](implicit um: PreprocessedFromEntityUnmarshaller[T], ev: ru.TypeTag[T], writes: Writes[T], reads: Reads[T]): In[T] = new In()
    def apply[T](example: T)(implicit um: PreprocessedFromEntityUnmarshaller[T], ev: ru.TypeTag[T], writes: Writes[T], reads: Reads[T]): In[T] = new In(Some(example))
  }
}

object MarshallingDDirectives extends MarshallingDDirectives 
开发者ID:evolution-gaming,项目名称:akka-http-documenteddsl,代码行数:28,代码来源:MarshallingDDirectives.scala


示例5: 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


示例6: OrgId

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

import play.api.libs.json.{JsNumber, Json, Reads, Writes}

object OrgId {
  // Json serdes for our wrapper class
  implicit val reader = Reads.of[Long].map(OrgId.apply)
  implicit val writer = Writes { (orgId: OrgId) =>
    JsNumber(orgId.id)
  }
}
case class OrgId(id: Long) extends AnyVal

object OrgInfo {
  implicit val jsonFormats = Json.format[OrgInfo]
}
case class OrgInfo(id: OrgId, name: String, status: Int) 
开发者ID:lloydmeta,项目名称:reculture-shields,代码行数:18,代码来源:OrgInfo.scala


示例7: AccessTokenResponse

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

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

import scala.concurrent.duration.FiniteDuration

case class AccessTokenResponse(accessToken: String,
                               expiresIn: FiniteDuration,
                               scope: List[String],
                               grantType: GrantType,
                               realm: String,
                               tokenType: TokenType)

object AccessTokenResponse {
  implicit val accessTokenResponseWrites: Writes[AccessTokenResponse] = Writes(
    (accessTokenResponse: AccessTokenResponse) =>
      Json.obj(
        "access_token" -> accessTokenResponse.accessToken,
        "expires_in"   -> accessTokenResponse.expiresIn.toSeconds,
        "scope"        -> accessTokenResponse.scope,
        "grant_type"   -> accessTokenResponse.grantType.id,
        "token_type"   -> accessTokenResponse.tokenType.id,
        "realm"        -> accessTokenResponse.realm
    ))
} 
开发者ID:zalando-incubator,项目名称:OAuth2-mock-play,代码行数:26,代码来源:AccessTokenResponse.scala


示例8: TokeninfoResponse

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

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

import scala.concurrent.duration.FiniteDuration

case class TokeninfoResponse(accessToken: String,
                             grantType: GrantType,
                             expiresIn: FiniteDuration,
                             tokenType: TokenType,
                             realm: String,
                             uid: String,
                             scope: List[String])

object TokeninfoResponse {
  implicit val tokeninfoResponseWrites: Writes[TokeninfoResponse] = Writes(
    (tokeninfoResponse: TokeninfoResponse) =>
      Json.obj(
        "access_token" -> tokeninfoResponse.accessToken,
        "grant_type"   -> tokeninfoResponse.grantType.id,
        "expires_in"   -> tokeninfoResponse.expiresIn.toSeconds,
        "scope"        -> tokeninfoResponse.scope,
        "realm"        -> tokeninfoResponse.realm,
        "token_type"   -> tokeninfoResponse.tokenType.id,
        "uid"          -> tokeninfoResponse.uid
    )
  )
} 
开发者ID:zalando-incubator,项目名称:OAuth2-mock-play,代码行数:29,代码来源:TokeninfoResponse.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: ProjectResult

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

import models.results.Template1Results.Template1Results
import models.results.Template2Results.Template2Results
import models.results.Template3Results.Template3Results
import models.results.Template4Results.Template4Results
import play.api.libs.functional.syntax._
import play.api.libs.json.{JsValue, Json, Reads, Writes}

trait ProjectResult

object ProjectResult {

  implicit val tempResultR: Reads[ProjectResult] =
    Json.format[Template1Results].map(x => x: ProjectResult) or
      Json.format[Template2Results].map(x => x: ProjectResult) or
      Json.format[Template3Results].map(x => x: ProjectResult) or
      Json.format[Template4Results].map(x => x: ProjectResult)


  implicit val tempResultW = new Writes[ProjectResult] {
    def writes(projectResult: ProjectResult): JsValue = {
      projectResult match {
        case m: Template1Results => Json.toJson(m)
        case m: Template2Results => Json.toJson(m)
        case m: Template3Results => Json.toJson(m)
        case m: Template4Results => Json.toJson(m)
        case _ => Json.obj("error" -> "wrong Json")
      }
    }
  }

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


示例11: 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


示例12: OAuthController

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

import models._
import javax.inject._
import play.api._
import play.api.mvc._
import play.api.libs.json.{Json, Writes}
import play.api.mvc.{Action, Controller}
import scalikejdbc._
import scalikejdbc.config._

import scala.concurrent.Future
import scalaoauth2.provider._
import scalaoauth2.provider.OAuth2ProviderActionBuilders._

import models.oauth.{OAuthDataHandler, OAuthTokenEndpoint}

@Singleton
class OAuthController @Inject() (dataHandler: OAuthDataHandler) extends Controller with OAuth2Provider {

  implicit val authInfoWrites = new Writes[AuthInfo[Account]] {
    def writes(authInfo: AuthInfo[Account]) = {
      Json.obj(
        "account" -> Json.obj(
          "email" -> authInfo.user.email
        ),
        "clientId" -> authInfo.clientId,
        "redirectUri" -> authInfo.redirectUri
      )
    }
  }

  override val tokenEndpoint = new OAuthTokenEndpoint

  def accessToken = Action.async { implicit request =>
    issueAccessToken(dataHandler)
  }

} 
开发者ID:trumanw,项目名称:cloud-oauth-play,代码行数:40,代码来源:OAuthController.scala


示例13: 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


示例14: node

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

import play.api.libs.json.{JsPath, Writes}

import play.api.libs.functional.syntax._

trait FsElement {
  def node: FsNode
}

object FsElement {

  implicit val fsElementWrites: Writes[FsElement] = (
    (JsPath \ "id").write[String] and
    (JsPath \ "location").write[String] and
    (JsPath \ "name").write[String] and
    (JsPath \ "type").write[String] and
    (JsPath \ "creation").write[String] and
    (JsPath \ "modification").write[String] and
    (JsPath \ "hidden").write[Boolean] and
    //(JsPath \ "creator").write[Account] and
    (JsPath \ "content").lazyWriteNullable(Writes.seq[FsElement](fsElementWrites)) and
    (JsPath \ "sources").lazyWriteNullable(Writes.seq[FileSource](FileSource.fileSourceWrites))
  )(element => (
    element.node.id.toString,
    element.node.location.toString,
    element.node.name,
    element.node.nodeType,
    element.node.creation.toString,
    element.node.modification.toString,
    element.node.hidden,
    //element.node.creator
    element match {
      case dir: Directory if dir.content.nonEmpty => Some(dir.content)
      case _ => None
    },
    element match {
      case file: File => Some(file.sources)
      case _ => None
    })
  )
} 
开发者ID:Cumulus-Cloud,项目名称:cumulus,代码行数:43,代码来源:FsElement.scala


示例15: FileSource

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

import java.util.UUID

import org.joda.time.DateTime
import play.api.libs.functional.syntax._
import play.api.libs.json.{JsPath, Writes}
import storage.FileStorageEngine


case class FileSource(
  id: UUID,
  size: BigInt,
  hash: String,
  cipher: Option[String],
  compression: Option[String],
  key: Option[String],
  storageEngine: String,
  storageEngineVersion: String,
  creation: DateTime
)

object FileSource {

  def initFrom(engine: FileStorageEngine): FileSource = FileSource(
    UUID.randomUUID(),
    0,
    "d41d8cd98f00b204e9800998ecf8427e", // MD5 of an empty string/file
    None,
    None,
    None,
    engine.name,
    engine.version,
    DateTime.now()
  )

  implicit val fileSourceWrites: Writes[FileSource] = (
    (JsPath \ "id").write[String] and
    (JsPath \ "size").write[Int] and
    (JsPath \ "hash").write[String] and
    (JsPath \ "cipher").write[String] and
    (JsPath \ "compression").write[String] and
    (JsPath \ "storageEngine").write[String] and
    (JsPath \ "storageEngineVersion").write[String] and
    (JsPath \ "creation").write[DateTime]
  )(source => (
    source.id.toString,
    source.size.toInt,
    source.hash,
    source.cipher.getOrElse("none"),
    source.compression.getOrElse("none"),
    source.storageEngine,
    source.storageEngineVersion,
    source.creation)
  )
} 
开发者ID:Cumulus-Cloud,项目名称:cumulus,代码行数:57,代码来源:File.scala


示例16: CaseClasses

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

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


object CaseClasses {
  case class ChatterInfo(id:String, name:String)
  case class IncomingMessage(text:String, lat:Double, lng:Double, chatterInfo: ChatterInfo)

  implicit val chatterInfoWrites = new Writes[ChatterInfo] {
    def writes(chatterInfo: ChatterInfo) = Json.obj(
      "name" -> chatterInfo.name,
      "id" -> chatterInfo.id
    )
  }

  implicit val incomingMessageWrites = new Writes[IncomingMessage] {
    def writes(incomingMessage: IncomingMessage) = Json.obj(
      "text" -> incomingMessage.text,
      "lat" -> incomingMessage.lat,
      "lng" -> incomingMessage.lng,
      "chatterInfo" -> Json.toJson(incomingMessage.chatterInfo)
    )
  }



def incomingMessageToJson(incomingMessage: IncomingMessage) : String = {
  Json.toJson(incomingMessage).toString()
}

} 
开发者ID:Purdue-ACM-SIGAPP,项目名称:uproar-backend-scala,代码行数:33,代码来源:CaseClasses.scala


示例17: SuppliersController

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

import javax.inject._
import models.daos.{AbstractBaseDAO, BaseDAO}
import models.entities.Supplier
import models.persistence.SlickTables.SuppliersTable
import play.api.libs.json.{Json, Writes}
import play.api.mvc._
import scala.concurrent.{Future, ExecutionContext}

@Singleton
class SuppliersController @Inject()(suppliersDAO : AbstractBaseDAO[SuppliersTable,Supplier])(implicit exec: ExecutionContext) extends Controller {

  implicit val supplierWrites = new Writes[Supplier] {
    def writes(sup: Supplier) = Json.obj(
      "id" -> sup.id,
      "name" -> sup.name,
      "desc" -> sup.desc
    )
  }

  def supplier(id : Long) = Action.async {
    suppliersDAO.findById(id) map { sup => sup.fold(NoContent)(sup => Ok(Json.toJson(sup))) }
  }

  def insertSupplier = Action.async(parse.json) {
    request => {
      {
        for {
          name <- (request.body \ "name").asOpt[String]
          desc <- (request.body \ "desc").asOpt[String]
        } yield {
          suppliersDAO.insert(Supplier(0, name, desc)) map { n => Ok("Id of Supplier Added : " + n) }
        }
      }.getOrElse(Future{BadRequest("Wrong json format")})
    }
  }

} 
开发者ID:CC5111,项目名称:Definitely-Not-Spotify,代码行数:40,代码来源:SuppliersController.scala


示例18: 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)
  }
} 
开发者ID:getmetorajesh,项目名称:rj_play_slick_events,代码行数:35,代码来源:EndpointResponse.scala


示例19: UserSocket

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

import actors.UserSocket.{ChatMessage, Message}
import actors.UserSocket.Message.messageReads
import akka.actor.{Actor, ActorLogging, ActorRef, Props}
import akka.cluster.pubsub.DistributedPubSub
import akka.cluster.pubsub.DistributedPubSubMediator.{Publish, Subscribe}
import akka.event.LoggingReceive
import play.api.libs.json.{Writes, JsValue, Json}
import play.twirl.api.HtmlFormat

import scala.xml.Utility

object UserSocket {
  def props(user: String)(out: ActorRef) = Props(new UserSocket(user, out))

  case class Message(msg: String)

  object Message {
    implicit val messageReads = Json.reads[Message]
  }

  case class ChatMessage(user: String, text: String)

  object ChatMessage {
    implicit val chatMessageWrites = new Writes[ChatMessage] {
      def writes(chatMessage: ChatMessage): JsValue = {
        Json.obj(
          "type" -> "message",
          "user" -> chatMessage.user,
          "text" -> multiLine(chatMessage.text)
        )
      }
    }

    private def multiLine(text: String) = {
      HtmlFormat.raw(text).body.replace("\n", "<br/>")
    }
  }
}

class UserSocket(uid: String, out: ActorRef) extends Actor with ActorLogging {

  val topic = "chat"

  val mediator = DistributedPubSub(context.system).mediator

  mediator ! Subscribe(topic, self)

  def receive = LoggingReceive {
    case js: JsValue =>
      js.validate[Message](messageReads)
        .map(message => Utility.escape(message.msg))
        .foreach { msg => mediator ! Publish(topic, ChatMessage(uid, msg))}

    case c:ChatMessage => out ! Json.toJson(c)
  }
} 
开发者ID:onegrx,项目名称:playakkachat,代码行数:59,代码来源:UserSocket.scala


示例20: UserController

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

import models.user.User
import play.api.libs.functional.syntax._
import play.api.libs.json.{JsPath, Json, Writes}
import play.api.mvc._


class UserController extends Controller{
  def list = Action { implicit request =>
    val users = User.fetchAll()
    Ok(Json.toJson(users))
  }

  implicit val locationWrites: Writes[User] = (
    (JsPath \ "id").write[Int] and
      (JsPath \ "username").write[String] and
      (JsPath \ "password").write[String]
    ) (unlift(User.unapply))
} 
开发者ID:beisser,项目名称:play2SkeletonApplication,代码行数:21,代码来源:UserController.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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