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

Scala Reads类代码示例

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

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



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

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


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


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


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


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


示例7: RequestSerializer

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

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

import play.api.libs.json.{Reads, __, JsValue}
import play.api.libs.functional.syntax._

object RequestSerializer {
  val DefaultValue = ""

  def deserialize(id: Long = 0, defaultTitle: String = DefaultValue, defaultAbbr: String = DefaultValue): Reads[Country] = (
    (__ \ 'country \ 'title).readNullable[String] and
    (__ \ 'country \ 'abbreviation).readNullable[String]
  )((titleOpt: Option[String], abbreviationOpt: Option[String]) => {
     val title = titleOpt.getOrElse(defaultTitle)
     val abbreviation = abbreviationOpt.getOrElse(defaultAbbr)

    Country(id, title, abbreviation, true)
  })

  def deserialize(request: JsValue, record: Future[Option[Country]]): Future[Option[Country]] = {
    record map { theRecord =>
      theRecord.map(exitingRecord => request.as[Country](deserialize(exitingRecord.id, exitingRecord.title, exitingRecord.abbreviation)))
    }
  }
} 
开发者ID:dsounded,项目名称:money_exchanger,代码行数:28,代码来源:Serializer.scala


示例8: ReceivedMessageConverters

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

import com.amazonaws.services.sqs.model.Message
import domain.common.{ MessageToken, ProcessableMessage, ReceivedMessage, UnprocessableMessage }
import play.api.libs.json.{ JsError, JsSuccess, Json, Reads }

object ReceivedMessageConverters {

  def toReceivedMessage[T](message: Message)(implicit reads: Reads[T]): ReceivedMessage[T] = {
    val json = Json.parse(message.getBody)
    val result = Json.fromJson(json)
    val token = MessageToken(message.getReceiptHandle)
    result match {
      case JsSuccess(t, _) => ProcessableMessage(t, token)
      case JsError(e) =>
        val errorMessage = s"messageId: ${ message.getMessageId }, reason: ${ Json.stringify(JsError.toJson(e)) }"
        UnprocessableMessage(new IllegalArgumentException(errorMessage), token)
    }
  }
} 
开发者ID:cm-wada-yusuke,项目名称:ecn-news,代码行数:21,代码来源:ReceivedMessageConverters.scala


示例9: writes

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

import models.Person
import org.joda.time.DateTime
import org.scalatestplus.play.{ OneAppPerTest, PlaySpec }
import play.api.libs.functional.syntax._
import play.api.libs.json.{ JsPath, Json, Reads, Writes }
import play.api.mvc.Result
import play.api.test.Helpers._
import play.api.test.{ FakeHeaders, FakeRequest }

import scala.concurrent.Future

trait PersonTestHelper extends PlaySpec with OneAppPerTest {

  private val PostHeaders = FakeHeaders(Seq("Content-type" -> "application/json"))

  private implicit val PersonWrites = new Writes[Person] {
    def writes(person: Person) = Json.obj(
      "id" -> person.id,
      "name" -> person.name,
      "age" -> person.age,
      "lastUpdate" -> person.lastUpdate
    )
  }

  private implicit val PersonReads: Reads[Person] = (
    (JsPath \ "id").read[Long] and
    (JsPath \ "name").read[String] and
    (JsPath \ "age").read[Int] and
    (JsPath \ "lastUpdate").read[DateTime]
  )(Person.apply _)

  def getPeople: Future[Result] = {
    val postRequest = FakeRequest(GET, controllers.routes.PersonController.returnPeople().url)
    route(app, postRequest).get
  }

  def postPerson(person: Person): Future[Result] = {
    val json = Json.toJson(person)
    val request = FakeRequest(POST, controllers.routes.PersonController.createPerson().url, PostHeaders, json)
    route(app, request).get
  }

  def persons(response: Future[Result]): Seq[Person] = {
    Json.fromJson[Seq[Person]](Json.parse(contentAsString(response))).get
  }
} 
开发者ID:marciogualtieri,项目名称:PersonService,代码行数:49,代码来源:PersonTestHelper.scala


示例10: createToken

//设置package包名称以及导入依赖的类
package im.actor.server.oauth

import akka.http.scaladsl.unmarshalling.PredefinedFromEntityUnmarshallers._
import akka.http.scaladsl.unmarshalling._
import akka.stream.Materializer
import play.api.libs.functional.syntax._
import play.api.libs.json.{ JsPath, Json, Reads }

trait Implicits {

  implicit val materializer: Materializer

  implicit val tokenReads: Reads[Token] =
    ((JsPath \ "access_token").read[String] and
      (JsPath \ "token_type").read[String] and
      (JsPath \ "expires_in").read[Long] and
      (JsPath \ "refresh_token").readNullable[String])(createToken _)

  implicit val profileReads: Reads[Profile] =
    ((JsPath \ "email").read[String] and
      (JsPath \ "family_name").readNullable[String] and
      (JsPath \ "name").readNullable[String] and
      (JsPath \ "given_name").readNullable[String] and
      (JsPath \ "picture").readNullable[String] and
      (JsPath \ "gender").readNullable[String] and
      (JsPath \ "locale").readNullable[String])(Profile)

  private def createToken(accessToken: String, tokenType: String, expiresIn: Long, refreshToken: Option[String]) =
    Token(accessToken, tokenType, expiresIn, refreshToken)

  implicit val toOAuthToken: FromResponseUnmarshaller[Option[Token]] = Unmarshaller { implicit ec ? resp ?
    Unmarshal(resp.entity).to[String].map { body ?
      Json.parse(body).validate[Token].fold(errors ? None, token ? Some(token))
    }
  }

  implicit val toProfile: FromResponseUnmarshaller[Option[Profile]] = Unmarshaller { implicit ec ? resp ?
    Unmarshal(resp.entity).to[String].map { body ?
      Json.parse(body).validate[Profile].fold(errors ? None, profile ? Some(profile))
    }
  }
} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:43,代码来源:Implicits.scala


示例11: FoldersRequest

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

import play.api.libs.json.{Json, Reads}
import services.moysklad.{Meta, PagedRequest, PagedResponse, pagedResponseReads}

class FoldersRequest extends PagedRequest[Folder] {
  override def endpoint: String = "/entity/productfolder"
}

object FoldersRequest {
  def apply(): FoldersRequest = new FoldersRequest
}

case class Folder(meta: Meta, name: String, pathName: Option[String]) extends Entity

object Folder {
  implicit val folderReads: Reads[Folder] = Json.reads[Folder]
  implicit val folderResponseReads: Reads[PagedResponse[Folder]] = pagedResponseReads[Folder]()
} 
开发者ID:SeriousDron,项目名称:moysklad-reports,代码行数:20,代码来源:Folder.scala


示例12: RetailDemandRequest

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


import java.time.{LocalDate, LocalDateTime}

import play.api.libs.json.{Json, Reads}
import services.moysklad._


class RetailDemandRequest(val updatedFrom: LocalDate, val updatedTo: LocalDate = LocalDate.now()) extends PagedRequest[RetailDemand](){
  override val endpoint: String = "/entity/retaildemand"

  override def queryString: Seq[(String, String)] = {
    super.queryString ++ Seq(
      ("updatedFrom", formatDateTime(updatedFrom)),
      ("updatedTo", formatDateTime(updatedTo)),
      ("expand", "positions,assortment")
    )
  }
}

case class Position(assortment: WrappedMeta, price: Int, quantity: Int)
case class RetailDemand(id: String, sum: Int, positions: PagedResponse[Position], moment: LocalDateTime, owner: WrappedMeta)

object RetailDemand {
  implicit val positionReads: Reads[Position] = Json.reads[Position]
  implicit val positionResponseReads: Reads[PagedResponse[Position]] = pagedResponseReads[Position]()
  implicit val retailDemandReads: Reads[RetailDemand] = Json.reads[RetailDemand]
  implicit val retailDemandResponseReads: Reads[PagedResponse[RetailDemand]] = pagedResponseReads[RetailDemand]()
} 
开发者ID:SeriousDron,项目名称:moysklad-reports,代码行数:31,代码来源:RetailDemand.scala


示例13: Question

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

import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import play.api.libs.json._
import play.api.libs.json.Reads
import play.api.libs.functional.syntax._
import slick.driver.MySQLDriver.api.{Tag => SlickTag}
import slick.driver.MySQLDriver.api._
import com.github.tototoshi.slick.MySQLJodaSupport._

case class Question(id: Option[Long], title: String, content: String,
  created_by: Option[Long], correct_answer: Option[Long],
  created_at: Option[DateTime] = None, updated_at: Option[DateTime] = None)

object Question {
//  implicit val format = Json.format[Question]

  implicit val questionReads: Reads[Question] = (
    (JsPath \ "id").readNullable[Long] and
    (JsPath \ "title").read[String] and
      (JsPath \ "content").read[String] and
      (JsPath \ "created_by").readNullable[Long] and
      (JsPath \ "correct_answer").readNullable[Long] and
      (JsPath \ "created_at").readNullable[DateTime] and
      (JsPath \ "updated_at").readNullable[DateTime]
  )(Question.apply _)

  implicit val questionWrites = Json.writes[Question]
}

class QuestionTable(tag: SlickTag) extends Table[Question](tag, "questions") {
//  import utils.CustomColumnTypes._
//  val dtf = DateTimeFormat.forPattern("yyyy-MM-dd hh:mm:ss")

  def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
  def title = column[String]("title")
  def content = column[String]("content")
  def created_by = column[Option[Long]]("created_by")
  def correct_answer = column[Option[Long]]("correct_answer")
  def created_at = column[Option[DateTime]]("created_at", O.Default(Some(new DateTime)))
  def updated_at = column[Option[DateTime]]("updated_at")

  def * = (id.?, title, content, created_by, correct_answer,
    created_at, updated_at) <> ((Question.apply _).tupled, Question.unapply)

  def creator = foreignKey("creator_fk", created_by, TableQuery[UserTable])(_.id.get)
  def answer = foreignKey("answer_fk", correct_answer, TableQuery[AnswerTable])(_.id)
} 
开发者ID:greven77,项目名称:PlaySlickTest,代码行数:50,代码来源:Question.scala


示例14: FormatInstancesSpec

//设置package包名称以及导入依赖的类
package com.iravid.playjsoncats

import org.scalatest.FunSuite
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.typelevel.discipline.scalatest.Discipline
import cats.laws.discipline._
import cats.kernel.instances.all._

import play.api.libs.json.{ Format, Writes, Reads }

class FormatInstancesSpec extends FunSuite with Discipline with GeneratorDrivenPropertyChecks with FormatInstances {
  import Arbitraries._

  checkAll("Format", InvariantTests[Format].invariant[String, String, String])
}

class ReadsInstancesSpec extends FunSuite with Discipline with GeneratorDrivenPropertyChecks with ReadsInstances {
  import Arbitraries._

  checkAll("Reads", FunctorTests[Reads].functor[String, String, String])
  checkAll("Reads", ApplicativeTests[Reads].applicative[String, String, String])
  checkAll("Reads", MonadTests[Reads].monad[String, String, String])
}

class WritesInstancesSpec extends FunSuite with Discipline with GeneratorDrivenPropertyChecks with WritesInstances {
  import Arbitraries._

  checkAll("Reads", ContravariantTests[Writes].contravariant[String, String, String])
} 
开发者ID:iravid,项目名称:play-json-cats,代码行数:30,代码来源:FormatInstancesSpec.scala


示例15: OauthCode

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


import org.joda.time.{DateTime, Duration}
import play.api.libs.functional.syntax._
import play.api.libs.json.{JsPath, Json, OWrites, Reads}

import scala.util.Random



case class OauthCode(code : String, user: User, client : OauthClient) {
  val created = new DateTime(new java.util.Date())

  // currently codes are valid for one day
  def isExpired : Boolean = created.plus(new Duration(24L*60L*60L*1000L)).isBeforeNow
}

object OauthCode {
  def apply(user: User, client: OauthClient) : OauthCode = OauthCode(Random.alphanumeric.take(100).mkString, user, client)
//  implicit val oauthCodeJsonFormat = Json.format[OauthCode]
  implicit val profileWrites : OWrites[OauthCode] = (
    (JsPath \ "code").write[String] and
      (JsPath \ "user").write[User] and
      (JsPath \ "client").write[OauthClient]
    )(unlift(OauthCode.unapply))
  implicit val profileReads : Reads[OauthCode] = (
    (JsPath \ "code").read[String] and
      (JsPath \ "user").read[User] and
      (JsPath \ "client").read[OauthClient]
    )((code, user, client) => OauthCode(code, user, client))
} 
开发者ID:Viva-con-Agua,项目名称:drops,代码行数:33,代码来源:OauthCode.scala


示例16: BaseController

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

import com.mohiva.play.silhouette.api.Silhouette
import com.mohiva.play.silhouette.api.actions.{SecuredRequest, UserAwareRequest}
import play.api.libs.json.{JsValue, Reads}
import play.api.mvc._
import utils.AppLogger
import utils.auth.DefaultEnv

import scala.concurrent.{Future}

abstract class BaseController(silhouette: Silhouette[DefaultEnv]) extends Controller with AppLogger {

  protected def unmarshalJsValue[R](request: Request[JsValue])(block: R => Future[Result])(implicit rds: Reads[R]): Future[Result] =
    request.body.validate[R](rds).fold(
      valid = block,
      invalid = e => {
      val error = e.mkString
      log.error(error)
      Future.successful(BadRequest(error))
    }
    )

  def withoutSession(action: String)(block: UserAwareRequest[DefaultEnv, AnyContent] => Future[Result]) = {
    silhouette.UserAwareAction.async { implicit request =>
      block(request)
    }
  }

  def withSession(action: String)(block: (SecuredRequest[DefaultEnv, AnyContent]) => Future[Result]) = {
    silhouette.UserAwareAction.async { implicit request =>
      request.identity match {
        case Some(u) =>
          val auth = request.authenticator.getOrElse(throw new IllegalStateException("You're not logged in."))
          block(SecuredRequest(u, auth, request))
        case None =>
          Future.successful(Unauthorized("You are not authorized to access this resource"))
      }
    }
  }

  def withAdminSession(action: String)(block: (SecuredRequest[DefaultEnv, AnyContent]) => Future[Result]) = {
    silhouette.UserAwareAction.async { implicit request =>
      request.identity match {
        case Some(u) =>
          if (u.role == "admin") {
            val auth = request.authenticator.getOrElse(throw new IllegalStateException("You're not logged in."))
            block(SecuredRequest(u, auth, request))
          } else {
            Future.successful(Unauthorized("You are not authorized to access this resource"))
          }

        case None =>
          Future.successful(Unauthorized("You are not authorized to access this resource"))
      }
    }
  }
} 
开发者ID:iriddhi,项目名称:mis,代码行数:59,代码来源:BaseController.scala


示例17: View

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

import play.api.libs.json.{Json, OWrites, Reads}

sealed trait View {

}

object View {
  case class Gravity(x: Double, y: Double, z: Double, userId: Long, name: String) extends View
  case class Message(message: String, userId: Long, name: String) extends View
  case class Event(value: String, userId: Long, name: String) extends View

  trait JsonReader {
    implicit val testReader: Reads[Message] = Json.reads[Message]
  }
  trait JsonWriter {
    implicit val testWriter: OWrites[Message] = Json.writes[Message]
    implicit val eventWriter: OWrites[Event] = Json.writes[Event]
    implicit val gravityWriter = Json.writes[Gravity]
  }
} 
开发者ID:Augment8,项目名称:slot,代码行数:23,代码来源:View.scala


示例18: Envelope

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

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

sealed trait User {

}

case class Envelope(`type`: String,value: JsValue)

case class ChangeName(name: String) extends User
case class PressButton(value: String) extends User
case class ReleaseButton(value: String) extends User
case class SessionId(sessionId: Long) extends User
case class Gravity(x: Double, y: Double, z: Double) extends User
case class Test(message: String) extends User

trait JsonFormat {
  implicit val envelopeJsonRead: Reads[Envelope] = Json.reads[Envelope]

  implicit val sessionIdJsonRead: Reads[SessionId] = Json.reads[SessionId]
  implicit val sessionIdJsonWrite: OWrites[SessionId] = Json.writes[SessionId]
  implicit val gravityJsonRead: Reads[Gravity] = Json.reads[Gravity]
  implicit val testJsonWrite: OWrites[Test] = Json.writes[Test]
  implicit val testJsonRead: Reads[Test] = Json.reads[Test]
  implicit val changeNameJsonRead: Reads[ChangeName] = Json.reads[ChangeName]
  implicit val pressButtonJsonRead: Reads[PressButton] = Json.reads[PressButton]
  implicit val releaseButtonJsonRead: Reads[ReleaseButton] = Json.reads[ReleaseButton]
} 
开发者ID:Augment8,项目名称:slot,代码行数:30,代码来源:User.scala


示例19: UserWebSocketActor

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

import actors.FeedbackAggregatorActor.{Feedback, StoreInfo, UnwatchFeedback, WatchFeedback}
import akka.actor._
import org.joda.time.{DateTime, DateTimeZone}
import play.api.libs.json.{JsValue, Json, Reads, Writes}

object UserWebSocketActor {
  def props(outActorRef: ActorRef, feedbackActor: ActorRef) = Props(new UserWebSocketActor(outActorRef, feedbackActor))
}

class UserWebSocketActor(outActorRef: ActorRef, feedbackActor: ActorRef) extends Actor {

  println("Making UserVoiceActor actor")

  // Subscribe to feedback
  feedbackActor ! WatchFeedback()

  def receive = {

    //Receive JSON from the client
    case msg: JsValue =>
      println(s"Got message: $msg")
      val surveyResponse = Feedback("1234", 9, "Pretty good", StoreInfo("1028AA", "99 Atlantic"), new DateTime(DateTimeZone.UTC))

    //Send feedback to the user when we receive it
    case [email protected](orderNumber, _, _, _, _) =>
      println(s"yo, feedback from order: $orderNumber")

      // TODO these belong in a companion object for SurveyResponse and StoreInfo
      implicit val yourJodaDateReads = Reads.jodaDateReads("yyyy-MM-dd'T'HH:mm:ss'Z'")
      implicit val yourJodaDateWrites = Writes.jodaDateWrites("yyyy-MM-dd'T'HH:mm:ss'Z'")
      implicit val storeInfoFormat = Json.format[StoreInfo]
      implicit val surveyResponseFormat = Json.format[Feedback]

      outActorRef ! Json.toJson(feedback)
  }

  
  override def postStop() = {
    feedbackActor ! UnwatchFeedback()
    println("UserVoiceActor actor stopped")
  }
} 
开发者ID:ChrisCooper,项目名称:customer-feedback-screen,代码行数:45,代码来源:UserWebSocketActor.scala


示例20: OrderController

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

import models.Order
import play.api.libs.json.{Json, Reads}
import play.api.mvc.{Action, Controller}
import play.twirl.api.Html
import services.{OrderService, PlacedOrders}

import scala.concurrent.{ExecutionContext, Future}

class OrderController(orderService: OrderService,
                      placedOrders: PlacedOrders)(
    implicit ec: ExecutionContext)
    extends Controller {

  def ordersGet = Action {
    Ok(Json.toJson(placedOrders.allOrders.get))
  }

  def ordersPost =
    Action.async(parse.json(oneOrManyOrders)) { request =>
      val orders: List[Order] = request.body

      Future
        .traverse(orders)(orderService.saveNew)
        .map(list => Ok)
    }

  val oneOrManyOrders: Reads[List[Order]] =
    implicitly[Reads[Order]]
      .map(List(_))
      .orElse(implicitly[Reads[List[Order]]])

  def index = Action {
    Ok(Html(
      "<h1>Welcome</h1><p>Your new application is ready.</p>"))
  }

} 
开发者ID:leanovate,项目名称:contoso-conference-manager,代码行数:40,代码来源:OrderController.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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