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