本文整理汇总了Scala中play.api.libs.json._类的典型用法代码示例。如果您正苦于以下问题:Scala _类的具体用法?Scala _怎么用?Scala _使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了_类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: Helper
//设置package包名称以及导入依赖的类
package helpers
import models.project.Project
import models.project.Project.EmbeddedProject
import play.api.libs.json.{JsError, _}
object Helper {
// URLs
val StatsPath = "http://api.sengab.com/v1/stats/"
val ResultPath = "http://api.sengab.com/v1/results/"
val CategoryPath = "http://api.sengab.com/v1/categories/"
val ProjectPath = "http://api.sengab.com/v1/projects/"
val UserPath = "http://api.sengab.com/v1/users/"
val ContributionsPath = "http://api.sengab.com/v1/contributions/"
val CreatedPostfixPath = "/created_projects"
val ContributionsPostfixPath = "/contributions"
// IDs
val UserIDPrefix = "user::"
val ActivityIDPrefix = "activity::"
val StatsIDPrefix = "stats::"
val ResultIDPrefix = "result::"
// expected filter keywords on list projects
val PopularKeyword = "popular"
val FeaturedKeyword = "featured"
val LatestKeyword = "latest"
val EnrolledKeyword = "enrolled"
val CreatedKeyword = "created"
def trimEntityID(entityID: String) = entityID.substring(entityID.indexOf("::") + 2)
}
示例2: index
//设置package包名称以及导入依赖的类
package controllers
import javax.inject._
import dao.UserDAO
import models.{Bad, User}
import play.api.mvc._
import play.api.libs.json.{JsError, JsSuccess, Json, _}
import play.api.Mode
import system.MyExecutionContext
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration
import scala.concurrent.Future
def index = Action {
Ok(views.html.index("Your new application is ready."))
}
implicit val userformat = Json.format[User]
def create = Action.async(parse.json) { implicit request =>
val validationResult: JsResult[User] = request.body.validate[User]
validationResult match {
case r: JsSuccess[User] =>
val user:User=r.get
val futureLong : Future[Long] = userDAO.insert(user)
futureLong.map{
result => Ok("success")
}
case r: JsError =>
scala.concurrent.Future {
val errors = JsError.toJson(r)
Ok(Json.toJson(Bad(Some(430), "bad.request", data = errors)))
}
}
}
def getAll = Action.async { implicit rs =>
val users : Future[Seq[User]] = userDAO.all()
users.map(u => Ok(Json.toJson(u)))
}
def deleteUser(id:Long) = Action.async { implicit request =>
userDAO.delete(id).map(num => Ok(Json.toJson(num)))
}
def getById(id:Long) =Action.async{ implicit request =>
userDAO.findById(id).map(num => Ok(Json.toJson(num)))
}
}
示例3: BitbucketStatus
//设置package包名称以及导入依赖的类
package com.pedrorijo91.status.model
import com.pedrorijo91.status.Config
import com.pedrorijo91.status.model.BitbucketStatus.ApiStatus
import org.joda.time.DateTime
import play.api.Logger
import play.api.libs.functional.syntax._
import play.api.libs.json.{Reads, _}
import scala.util.Try
case class BitbucketStatus(updatedAt: DateTime, status: ApiStatus.Value, description: String) extends HostStatus {
def datetime: String = updatedAt.toString(Config.dateTimeFormat)
}
object BitbucketStatus {
private val logger = Logger(this.getClass)
implicit val read: Reads[BitbucketStatus] = (
(JsPath \ "page" \ "updated_at").read[String].map(new DateTime(_)) and
(JsPath \ "status" \ "indicator").read[String].map(ApiStatus.findByName) and
(JsPath \ "status" \ "description").read[String]
) (BitbucketStatus.apply _)
object ApiStatus extends Enumeration {
val None, Minor, Major, Critical, Unknown = Value
def findByName(name: String): ApiStatus.Value = {
Try(ApiStatus.withName(name.toLowerCase.capitalize)).getOrElse {
logger.warn(s"Found unexpected Bitbucket API status: $name")
Unknown
}
}
}
}
示例4: ShapelessObjectJsonSpec
//设置package包名称以及导入依赖的类
package microtools.shapeless
import org.scalatest.MustMatchers
import org.scalatestplus.play.PlaySpec
import play.api.libs.json.{Json, _}
import shapeless.HNil
import shapeless.record._
import shapeless.syntax.singleton._
class ShapelessObjectJsonSpec extends PlaySpec with MustMatchers {
"Shapeless writes" should {
"serialize HNil to empty object" in {
import ShapelessObjectJson._
val json = Json.toJson(HNil)
json mustBe Json.obj()
}
"serialize Labeled HList to object" in {
import ShapelessObjectJson._
val json =
Json.toJson(('someInt ->> 1234) :: ('someStr ->> "string") :: ('someBool ->> true) :: HNil)
(json \ "someInt").as[Int] mustBe 1234
(json \ "someStr").as[String] mustBe "string"
(json \ "someBool").as[Boolean] mustBe true
}
}
"shapeless reads" should {
"deserialize HNil on any" in {
import ShapelessObjectJson._
Json.obj("bla" -> "blub").as[HNil] mustBe HNil
JsNull.as[HNil] mustBe HNil
}
"deserialize json object to labeled HList" in {
import ShapelessObjectJson._
type record = Record.`'someInt -> Int, 'someString -> String, 'someBool -> Boolean`.T
val result = Json
.obj("someString" -> "string", "someInt" -> 1234, "someBool" -> true)
.as[record]
result('someInt) mustBe 1234
result('someString) mustBe "string"
result('someBool) mustBe true
}
}
}
示例5: ResetPasswordMessage
//设置package包名称以及导入依赖的类
package access.authentication
import messaging.{SocketMessageType, ToServerSocketMessage, ToServerSocketMessageType}
import org.apache.commons.validator.routines.EmailValidator
import play.api.libs.functional.syntax._
import play.api.libs.json.Reads._
import play.api.libs.json.{Reads, _}
import scala.util.Try
case class ResetPasswordMessage(email: String, code: String, newPassword: String)
extends ToServerSocketMessage {
override val socketMessageType: SocketMessageType = ResetPasswordMessage.ResetPassword
private val emailValidator = EmailValidator.getInstance()
require(email.trim.nonEmpty)
require(code.trim.nonEmpty)
require(newPassword.trim.nonEmpty)
require(emailValidator.isValid(email.trim))
}
object ResetPasswordMessage {
implicit val resetPasswordMessageReads: Reads[ResetPasswordMessage] = (
(JsPath \ "email").read[String](email) and
(JsPath \ "code").read[String](minLength[String](1)) and
(JsPath \ "newPassword").read[String](minLength[String](1))
) (ResetPasswordMessage.apply _)
case object ResetPassword extends ToServerSocketMessageType {
override val description = "toServerResetPassword"
override def socketMessage(msg: JsValue): ResetPasswordMessage =
Try(resetPasswordMessageReads.reads(msg)).toOption.flatMap(_.asOpt).getOrElse(ResetPasswordMessage("1", "2" , "3"))
}
}
示例6: writes
//设置package包名称以及导入依赖的类
package connectors
import models._
import play.api.libs.json.{Json, Writes, _}
import scala.collection.mutable.ArrayBuffer // Combinator syntax
trait SalvoStatusFormatter {
implicit val salvoStatusWrites = new Writes[SalvoStatus] {
def writes(salvoStatus: SalvoStatus) : JsObject = {
if (salvoStatus.nextTurn != null) {
val hits = salvoStatus.hits
val game = salvoStatus.gameOver match {
case true => Json.obj("won" -> salvoStatus.nextTurn.id)
case false => Json.obj("player_turn" -> salvoStatus.nextTurn.id)
}
Json.obj(
"salvo" -> Json.obj(hits(0).position -> hits(0).status,
hits(1).position -> hits(1).status,
hits(2).position -> hits(2).status,
hits(3).position -> hits(3).status,
hits(4).position -> hits(4).status),
"game" -> game
)
}else{
Json.obj("message" -> "Game not found.check GameID.")
}
}
}
}
示例7: TeamsController
//设置package包名称以及导入依赖的类
package v1.teams
import com.github.scribejava.core.model.{OAuth1AccessToken, Response, Verb}
import models.DraftSummary
import play.api.libs.json.{Json, _}
import play.api.mvc.{Action, AnyContent, Controller, Request}
import services.RedisService._
import services.{RedisService, YahooOauthService}
import v1.YahooRoutes
import v1.JSParsers._
class TeamsController extends Controller{
implicit val draftSummaryReads = Json.reads[DraftSummary]
implicit val draftSummaryWrites = Json.writes[DraftSummary]
implicit val jsStringReads = Json.reads[JsString]
def getToken(implicit request: Request[AnyContent]): OAuth1AccessToken = {
val tokenString = request.headers.get("Authentication").getOrElse("")
new OAuth1AccessToken(tokenString, redis.get(tokenString).get)
}
def get(id: String) = Action { implicit request =>
val yahooResponse: Response = new YahooOauthService().makeRequest(Verb.GET, YahooRoutes.playersFromTeamReplaceId.replaceAll(":id", s"363.l.63462.t.$id"), getToken)
RedisService.checkDraftResults(getToken)
RedisService.getPlayerRankings(getToken)
val teamDraftSummary: DraftSummary = DraftSummary.generateDraftSummary(yahooResponse.getBody, id)
Ok(Json.toJson(teamDraftSummary))
}
def getTeams = Action { implicit request =>
val yahooRequest = new YahooOauthService().makeRequest(Verb.GET, YahooRoutes.usersTeams, getToken)
val usersTeamResponse = Json.parse(yahooRequest.getBody)
val teams = usersTeamResponse \ "team"
Ok(teams.toString)
}
}
示例8: EnumUtils
//设置package包名称以及导入依赖的类
package utils
import play.api.libs.json.{JsString, _}
object EnumUtils {
def enumReads[E <: Enumeration](enum: E): Reads[E#Value] = new Reads[E#Value] {
def reads(json: JsValue): JsResult[E#Value] = json match {
case JsString(s) => {
try {
JsSuccess(enum.withName(s))
} catch {
case _: NoSuchElementException => JsError(s"Enumeration expected of type: '${enum.getClass}', but it does not appear to contain the value: '$s'")
}
}
case _ => JsError("String value expected")
}
}
implicit def enumWrites[E <: Enumeration]: Writes[E#Value] = new Writes[E#Value] {
def writes(v: E#Value): JsValue = JsString(v.toString)
}
implicit def enumFormat[E <: Enumeration](enum: E): Format[E#Value] = {
Format(enumReads(enum), enumWrites)
}
}
示例9: SecretDetail
//设置package包名称以及导入依赖的类
package domains
import play.api.libs.functional.syntax._
import play.api.libs.json.{Writes, _}
case class SecretDetail(id: Option[Int], title: Option[String], itemId: Option[Int], itemName: Option[String], itemDesc: Option[String], securityLevel: Option[Int], itemContent: Option[String])
object SecretDetail {
implicit val reads: Reads[SecretDetail] = (
(__ \ "id").readNullable[Int] ~
(__ \ "title").readNullable[String] ~
(__ \ "itemId").readNullable[Int] ~
(__ \ "itemName").readNullable[String] ~
(__ \ "itemDesc").readNullable[String] ~
(__ \ "securityLevel").readNullable[Int] ~
(__ \ "itemContent").readNullable[String]
) (SecretDetail.apply _)
implicit lazy val writes: Writes[SecretDetail] = (
(__ \ "id").writeNullable[Int] ~
(__ \ "title").writeNullable[String] ~
(__ \ "itemId").writeNullable[Int] ~
(__ \ "itemName").writeNullable[String] ~
(__ \ "itemDesc").writeNullable[String] ~
(__ \ "securityLevel").writeNullable[Int] ~
(__ \ "itemContent").writeNullable[String]
) (unlift(SecretDetail.unapply))
}
case class RelationSecretItem(secretId: Int, itemId: Int, itemContent: String)
object RelationSecretItem {
implicit val reads: Reads[RelationSecretItem] = (
(__ \ "secretId").read[Int] ~
(__ \ "itemId").read[Int] ~
(__ \ "itemContent").read[String]
) (RelationSecretItem.apply _)
implicit lazy val writes: Writes[RelationSecretItem] = (
(__ \ "secretId").write[Int] ~
(__ \ "itemId").write[Int] ~
(__ \ "itemContent").write[String]
) (unlift(RelationSecretItem.unapply))
}
示例10: TransportRequest
//设置package包名称以及导入依赖的类
package domains
import play.api.libs.functional.syntax._
import play.api.libs.json.{Reads, Writes, _}
class TransportRequest(val publicKey: String, val info: Option[String]) {
override def toString = Json.toJson(this).toString()
}
object TransportRequest {
implicit val reads: Reads[TransportRequest] = (
(__ \ "publicKey").read[String] ~
(__ \ "info").readNullable[String]
) (TransportRequest.apply _)
implicit val writes: Writes[TransportRequest] = (
(__ \ "publicKey").write[String] ~
(__ \ "info").writeNullable[String]
) (unlift(TransportRequest.unapply))
def apply(publicKey: String, info: Option[String]): TransportRequest = {
info match {
case error if error.isEmpty => new TransportRequest(publicKey, info)
case _ => new TransportRequest(publicKey, info)
}
}
def unapply(arg: TransportRequest): Option[(String, Option[String])] = Some(arg.publicKey, arg.info)
}
示例11: UrbanResponse
//设置package包名称以及导入依赖的类
package models
import play.api.Logger
import play.api.libs.functional.syntax._
import play.api.libs.json.{Reads, _}
import scala.language.postfixOps
import scala.util.Try
case class UrbanResponse(resultType: UrbanResponseResultType.Value, definitions: List[UrbanTerm])
object UrbanResponse {
implicit val userReads: Reads[UrbanResponse] = (
(__ \ "result_type").read[String].map(UrbanResponseResultType.findByName) and
(__ \ "list").read[List[UrbanTerm]]
) (UrbanResponse.apply _)
}
object UrbanResponseResultType extends Enumeration {
val Exact = Value("exact")
val NoResults = Value("no_results")
val Unknown = Value("unknown")
def findByName(name: String): UrbanResponseResultType.Value = {
Try(UrbanResponseResultType.withName(name)).getOrElse {
Logger.warn(s"Found unexpected UrbanDictionary API result: $name")
Unknown
}
}
}
case class UrbanTerm(definition: String, permalink: String, thumbsUp: Int, thumbsDown: Int, author: String, example: String)
object UrbanTerm {
implicit val userReads: Reads[UrbanTerm] = (
(__ \ "definition").read[String] and
(__ \ "permalink").read[String] and
(__ \ "thumbs_up").read[Int] and
(__ \ "thumbs_down").read[Int] and
(__ \ "author").read[String] and
(__ \ "example").read[String]
) (UrbanTerm.apply _)
}
示例12: JsonConverters
//设置package包名称以及导入依赖的类
package controllers.converters
import models._
import play.api.libs.json.{JsError, JsSuccess, Writes, _}
object JsonConverters {
implicit val userIdReads = idReads(jsonValue => UserId(jsonValue.toLong))
implicit val userIdWrites = idWrites[Long, UserId]()
implicit val commendIdReads = idReads(jsonValue => CommentId(jsonValue.toLong))
implicit val commentIdWrites = idWrites[Long, CommentId]()
implicit val githubRepoIdFormat = Json.format[GitHubRepositoryId]
implicit val userFormat = Json.format[User]
implicit val loginAttemptFormat = Json.format[LoginAttempt]
implicit val gitRepositoryFormat = Json.format[GitRepository]
implicit val commentFormat = Json.format[Comment]
implicit val newCommentFormat = Json.format[NewComment]
implicit val newCommentLikeFormat = Json.format[NewCommentLike]
implicit val commentLikeFormat = Json.format[CommentLike]
def idReads[T](constructor: String => T): Reads[T] = new Reads[T] {
override def reads(json: JsValue): JsResult[T] = json match {
case JsString(s) => JsSuccess(constructor(s))
case _ => JsError("String value expected")
}
}
def idWrites[ID, T <: ModelId[ID]](): Writes[T] = new Writes[T] {
override def writes(o: T): JsValue = JsString(o.value.toString)
}
}
示例13: RoleUtils
//设置package包名称以及导入依赖的类
package models.user
import play.api.data.validation.ValidationError
import play.api.libs.json.{Format, Json, Writes, _}
import slick.driver.PostgresDriver.api._
object RoleUtils{
private val roleMap:Map[Int, ClientRole] = Map(
0 -> Admin,
1 -> L1,
2 -> L2
)
def forId(id:Int) : ClientRole = roleMap.get(id).getOrElse(L1) // todo fix this.
implicit val mappedTypeMapper = MappedColumnType.base[ClientRole,Int](
r => r.id,
i => forId(i)
)
object ClientRoleReads extends Reads[ClientRole] {
override def reads(json: JsValue): JsResult[ClientRole] =
(json \ "id").asOpt[Int] match {
case Some(x) => JsSuccess(forId(x))
case None => JsError(ValidationError("No id value found in client role json object."))
}
}
object ClientRoleWrites extends Writes[ClientRole] {
override def writes(o: ClientRole): JsValue = Json.obj(
"id" -> o.id,
"n" -> o.prettyName
)
}
implicit val clientRoleFormats = Format(ClientRoleReads,ClientRoleWrites)
}
sealed trait ClientRole{
val id: Int
val prettyName:String
}
case object Admin extends ClientRole{
val id = 0
val prettyName:String = "Admin"
}
case object L1 extends ClientRole{
val id = 1
val prettyName:String = "L1"
}
case object L2 extends ClientRole{
val id = 2
val prettyName:String = "L2"
}
示例14: ApiToken
//设置package包名称以及导入依赖的类
package models
import play.api.libs.json.{ JsObject, Json, _ }
import play.api.libs.json.{ JsPath, Json, Reads, Writes }
import java.util.{ Date, UUID }
import play.api.libs.json.{ JsObject, Json, _ }
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.play.json.collection.JSONCollection
import reactivemongo.play.json.BSONFormats._
import scala.concurrent.ExecutionContext.Implicits.global
import org.joda.time.DateTime
import play.api.Logger
import reactivemongo.bson.{ BSONDateTime, BSONObjectID }
import play.api.libs.functional.syntax._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
case class ApiToken(
userId: Option[BSONObjectID],
token: String, // UUID 36 digits
apiKey: String,
expirationTime: DateTime
) {
def isExpired = expirationTime.isBeforeNow
}
object ApiToken {
import FakeDB.tokens
implicit val externalEventRead: Reads[ApiToken] = (
(JsPath \ "userId").readNullable[BSONObjectID] and
(JsPath \ "token").read[String] and
(JsPath \ "apiKey").read[String] and
(JsPath \ "expirationTime").read[DateTime]
)(ApiToken.apply _)
val externalEventWrites: Writes[ApiToken] = (
(JsPath \ "userId").writeNullable[BSONObjectID] and
(JsPath \ "token").write[String] and
(JsPath \ "apiKey").write[String] and
(JsPath \ "expirationTime").write[DateTime]
)(unlift(ApiToken.unapply))
implicit val apiTokenFormat = Json.format[ApiToken]
}
示例15: Name
//设置package包名称以及导入依赖的类
package models
import play.api.libs.functional.syntax._
import play.api.libs.json.{Format, Json, _}
case class Name(value: String)
object Name {
implicit val nameFormat = Json.format[Name]
}
case class DOB(value: String)
object DOB {
implicit val dobFormat = Json.format[DOB]
}
case class Pet(id: Option[Int], name: Name, dob: DOB, notes: String)
object Pet {
val petReads: Reads[Pet] = (
(JsPath \ "id").readNullable[Int] and
(JsPath \ "name").read[String].map { value => Name(value) } and
(JsPath \ "dateOfBirth").read[String].map { value => DOB(value) } and
(JsPath \ "notes").read[String]
) (Pet.apply _)
val petWrites: Writes[Pet] = (
(JsPath \ "id").writeNullable[Int] and
(JsPath \ "name").write[String].contramap { (name: Name) => name.value } and
(JsPath \ "dateOfBirth").write[String].contramap { (dob: DOB) => dob.value } and
(JsPath \ "notes").write[String]
) (unlift(Pet.unapply))
implicit val petFormat: Format[Pet] =
Format(petReads, petWrites)
}