本文整理汇总了Scala中play.api.libs.json.Writes类的典型用法代码示例。如果您正苦于以下问题:Scala Writes类的具体用法?Scala Writes怎么用?Scala Writes使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Writes类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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))
}
}
示例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
)
}
}
示例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
)
}
}
示例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
示例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
示例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)
示例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
))
}
示例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
)
)
}
示例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")
}
}
}
}
示例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")
}
}
}
}
示例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")
}
}
}
}
示例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)
}
}
示例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]
}
示例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
})
)
}
示例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)
)
}