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

Scala JsResult类代码示例

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

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



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

示例1: transformAsFuture

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

import play.api.libs.json.JsResult
import play.api.mvc.{Result, Controller}

import scala.concurrent.Future

trait ControllerUtils extends Logged {
  self: Controller =>

  def transformAsFuture[T](json: JsResult[T]): Future[T] =
    if (json.isSuccess) Future.successful(json.get)
    else {
      log.debug(s"unable to parse json value: $json")
      Future.failed(new Exception("error parsing json"))
    }

  val withRecover: PartialFunction[Throwable, Result] = {
    case e: Exception => BadRequest(s"bad request: ${e.getMessage}")
  }
} 
开发者ID:mronethere,项目名称:maze-runner,代码行数:22,代码来源:ControllerUtils.scala


示例2: UserResource

//设置package包名称以及导入依赖的类
package com.clemble.loveit.thank.model

import com.clemble.loveit.common.model.{Resource, UserID}
import com.clemble.loveit.common.util.WriteableUtils
import play.api.libs.json.{Format, JsResult, JsValue, Json}


  val verification: Option[ROVerification[Resource]]
}

object UserResource {

  def empty(user: UserID): UserResource = SimpleUserResource(user)

  implicit val jsonFormat: Format[UserResource] = new Format[UserResource] {
    override def reads(json: JsValue): JsResult[UserResource] = SimpleUserResource.jsonFormat.reads(json)
    override def writes(o: UserResource): JsValue = SimpleUserResource.jsonFormat.writes(SimpleUserResource(o.id, o.owns, o.verification))
  }

  implicit val writeable = WriteableUtils.jsonToWriteable[UserResource]()
}

private case class SimpleUserResource(
                               id: UserID,
                               owns: Set[Resource] = Set.empty,
                               verification: Option[ROVerification[Resource]] = None
                             ) extends UserResource

private object SimpleUserResource {
  implicit val jsonFormat = Json.format[SimpleUserResource]
} 
开发者ID:thankyo,项目名称:thank,代码行数:32,代码来源:UserResource.scala


示例3: Project

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

import javax.inject.Inject

import akka.actor.ActorRef
import akka.stream.scaladsl.Source
import akka.util.Timeout
import com.github.jeroenr.bson.BsonDocument
import com.github.jeroenr.bson.BsonDsl._
import helpers.BsonDocumentHelper._
import play.api.libs.json.{JsResult, JsSuccess, Json}
import play.api.modules.tepkinmongo.TepkinMongoApi

import scala.concurrent.Future
import scala.concurrent.duration._

case class Project(_id: String, name: String)

object Project {
  implicit val projectFormatter = Json.format[Project]
  def apply(bson: BsonDocument): JsResult[Project] = {
    Json.fromJson[Project](bson)
  }

  def toBsonDocument(project: Project): BsonDocument =
    ("_id" := project._id) ~
      ("name" := project.name)
}


class ProjectRepo @Inject() (tepkinMongoApi: TepkinMongoApi) {
  implicit val ec = tepkinMongoApi.client.ec
  implicit val timeout: Timeout = 5.seconds

  val projects = tepkinMongoApi.client("tepkin")("projects")

  def create(name: String): Future[Boolean] = {
    val project = "name" := name
    projects.insert(project).map(_.ok)
  }

  def all: Source[List[Project], ActorRef] = {
    projects.find(new BsonDocument()).map(l => l.map(Project(_)).collect {
      case JsSuccess(p, _ ) => p
    })
  }

  def insert(ps: List[Project]) =
    projects.insert(ps.map(Project.toBsonDocument))

  def findByName(name: String): Future[Option[Project]] = {
    val byId = "name" := name
    projects.findOne(byId).map(_.flatMap(Project(_).asOpt))
  }


} 
开发者ID:jonasanso,项目名称:play-tepkin-mongo,代码行数:58,代码来源:Project.scala


示例4: SourceActor

//设置package包名称以及导入依赖的类
package com.malliina.logstreams.ws

import com.malliina.logstreams.models._
import com.malliina.logstreams.ws.SourceMediator.{SourceInfo, SourceJoined}
import com.malliina.play.ws.{ClientActor, ClientContext}
import play.api.libs.json.{JsResult, JsValue, Json}

class SourceActor(app: AppName, ctx: ClientContext) extends ClientActor(ctx) {
  val src = LogSource(app, address)

  override def preStart(): Unit = {
    super.preStart()
    mediator ! SourceJoined(SourceInfo(src, ctx.out))
  }

  override def transform(message: JsValue): JsResult[JsValue] =
    message.validate[LogEvents].map(les => Json.toJson(toAppEvents(les)))

  def toAppEvents(logEvents: LogEvents) = {
    val appEvents = logEvents.events.map(event => AppLogEvent(src, event))
    AppLogEvents(appEvents)
  }
} 
开发者ID:malliina,项目名称:logstreams,代码行数:24,代码来源:SourceActor.scala


示例5: TSchemaUtil

//设置package包名称以及导入依赖的类
package com.gxq.learn.recontool.utils

import com.gxq.learn.recontool.entity.ReconToolTSchema
import org.apache.spark.SparkContext
import play.api.libs.json.Json
import play.api.libs.json.JsValue
import play.api.libs.json.JsResult
import play.api.libs.json.JsSuccess
import play.api.libs.json.JsPath
import play.api.libs.json.JsError
import scala.collection.SortedMap

object TSchemaUtil {
  def getTSchema(sc: SparkContext, fileUrl: String): ReconToolTSchema = {
    val jsonString = sc.textFile(fileUrl).collect().mkString
    implicit val rtReads = Json.reads[ReconToolTSchema]
    val jsonValue: JsValue = Json.parse(jsonString)
    val rtFromJson: JsResult[ReconToolTSchema] = Json.fromJson[ReconToolTSchema](jsonValue)
    val result = rtFromJson match {
      case JsSuccess(rt: ReconToolTSchema, path: JsPath) => rt
      case e: JsError                                    => throw new IllegalArgumentException(JsError.toJson(e).toString())
    }
    result
  }

  def getHeaderIndexMap(header: String): SortedMap[Int, String] = {
    var headMap = SortedMap[Int, String]()
    val hArr = header.split(",", -1)
    for (i <- 0 until hArr.length) {
      headMap = headMap + (i -> hArr(i).trim())
    }
    headMap
  }
} 
开发者ID:gong1989313,项目名称:spark-bigdata,代码行数:35,代码来源:TSchemaUtil.scala


示例6: PersonController

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

import models.{ErrorResponse, Person}
import play.api.data.validation.ValidationError
import play.api.libs.json.{JsPath, JsResult, JsValue, Json}
import play.api.mvc.{Action, AnyContent, Controller}
import ErrorResponse._

class PersonController extends Controller {
  def personById(personId: String): Action[AnyContent] = Action {
    Ok(personId)
  }

  def echo: Action[JsValue] = Action(parse.json) {
    implicit request =>
      val eitherPerson = validateParsedResult(request.body.validate[Person])
      eitherPerson.fold(
        errorResponse => BadRequest(Json.toJson(errorResponse)),
        person => Ok(Json.toJson(person))
      )
  }

  def validateParsedResult[T](jsResult: JsResult[T]): Either[ErrorResponse, T] =
    jsResult.fold(
      (errors: Seq[(JsPath, Seq[ValidationError])]) => {
        val map = fmtValidationResults(errors)
        Left(ErrorResponse("Validation Error", map))
      },
      (t: T) => Right(t)
    )
} 
开发者ID:calvinlfer,项目名称:play-framework-validation-example,代码行数:32,代码来源:PersonController.scala


示例7: ThingController

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

import com.takatori.hundredthings.dao.ThingDao
import com.takatori.hundredthings.models.Thing
import play.api.libs.json.{JsError, JsResult, Json}
import play.api.mvc.{Action, Controller}

import scala.concurrent.{ExecutionContext, Future}

class ThingController(thingDao: ThingDao)(implicit ec: ExecutionContext) extends Controller {

  def list(userId: Int) = Action.async { request =>
    thingDao.list(userId) map { things => Ok(Json.toJson(things)) }
  }

  def fetch(id: Int) = Action.async { request =>
    thingDao.fetch(id) map { thing => Ok(Json.toJson(thing)) }
  }

  def create(userId: Int) = Action.async(parse.json) { request =>
    val thingResult: JsResult[Thing] = request.body.validate[Thing]
    thingResult.fold(
      errors => Future.successful(BadRequest(Json.obj("status" -> "KO", "message" -> JsError.toJson(errors)))),
      thing => {
        thingDao.create(userId, thing) map { id =>
          Ok(Json.obj("status" -> "OK", "message" -> ("Place" +  id + "saved.")))
        }
      }
    )
  }

  def update(thingId: Int) = Action.async(parse.json) { request =>
    val thingResult: JsResult[Thing] = request.body.validate[Thing]
    thingResult.fold(
      errors => Future.successful(BadRequest(Json.obj("status" -> "KO", "message" -> JsError.toJson(errors)))),
      thing => {
        thingDao.update(thingId, thing) map { affetctedRows =>
          Ok(Json.obj("status" -> "OK", "message" -> ("Place '" + thing.title + "' update.")))
        }
      })
  }

  def delete(thingId: Int) = Action.async { request =>
    thingDao.delete(thingId) map { result => Ok(Json.toJson("Succeed in delete thing.")) }
  }
} 
开发者ID:takatori,项目名称:100things,代码行数:47,代码来源:ThingController.scala


示例8: UserController

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

import com.takatori.hundredthings.dao.UserDao
import com.takatori.hundredthings.models.User
import play.api.libs.json.{JsError, JsResult, Json}
import play.api.mvc.{Action, Controller}

import scala.concurrent.{ExecutionContext, Future}

class UserController(userDao: UserDao)(implicit ec: ExecutionContext) extends Controller {

  def fetchAll() = Action.async { request => userDao.all.map { users => Ok(Json.toJson(users)) } }

  def fetch(userId: Int) = Action.async { request =>
    userDao.fetch(userId) map { user => Ok(Json.toJson(user)) }
    //BadRequest(Json.obj("status" -> "KO", "message" -> JsError.toJson("not found")))
  }

  def insert() = Action.async(parse.json) { request =>
    val userResult: JsResult[User] = request.body.validate[User]
    // Future[Result]???????????
    userResult.fold(
      errors => Future.successful(BadRequest(Json.obj("status" -> "KO", "message" -> JsError.toJson(errors)))),
      user => {
        userDao.insert(user) map { id =>
            Ok(Json.obj("status" -> "OK", "message" -> ("Place '" + user.name + "' saved.")))
        }
      })
  }

  def update(userId: Int) = Action.async(parse.json) { request =>
    val userResult: JsResult[User] = request.body.validate[User]
    userResult.fold(
      errors => Future.successful(BadRequest(Json.obj("status" -> "KO", "message" -> JsError.toJson(errors)))),
      user => {
        userDao.update(userId, user) map { affetctedRows =>
          Ok(Json.obj("status" -> "OK", "message" -> ("Place '" + user.name + "' update.")))
        }
      })
  }

  def delete(userId: Int) = Action.async { request =>
    userDao.delete(userId) map { result => Ok(Json.toJson("Succeed in delete user.")) } // TODO: ??????
  }
} 
开发者ID:takatori,项目名称:100things,代码行数:46,代码来源:UserController.scala


示例9: Input

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

import play.api.libs.json.{ Format, Json, JsError, JsResult, JsSuccess }
import play.api.libs.json.{ JsValue, JsObject, JsString }

case class Input(action: String)
object Input {
  implicit val jsonFormat = new Format[Input] {
    def reads(json: JsValue): JsResult[Input] = {
      (json \ "action").validate[String].map(Input(_))
    }
    def writes(input: Input): JsValue = {
      Json.obj("action" -> input.action)
    }
  }
}

sealed trait Output
case object Talking extends Output
case class Talk(content: String) extends Output
case class Info(content: String) extends Output
case class Error(content: String) extends Output
case class Choices(choices: Map[String, String]) extends Output
object Output {
  implicit val jsonFormat = new Format[Output] {
    def reads(json: JsValue): JsResult[Output] = {
      (json \ "kind").validate[String].flatMap {
        case "talking" => JsSuccess(Talking)
        case "talk" => (json \ "message").validate[String].map(Talk(_))
        case "info" => (json \ "message").validate[String].map(Info(_))
        case "error" => (json \ "message").validate[String].map(Error(_))
        case "choices" => (json \ "choices").validate[Map[String, String]].map(Choices(_))
        case _ => JsError("Unknown kind")
      }
    }
    def writes(o: Output): JsValue = o match {
      case Talking => Json.obj("kind" -> "talking")
      case Talk(content) => Json.obj("kind" -> "talk", "message" -> content)
      case Info(content) => Json.obj("kind" -> "info", "message" -> content)
      case Error(content) => Json.obj("kind" -> "error", "message" -> content)
      case Choices(choices) => Json.obj(
        "kind" -> "choices",
        "choices" -> JsObject(choices.toSeq.map{ case (n, v) => n -> JsString(v) })
      )
    }
  }
} 
开发者ID:dohzya,项目名称:lifelines,代码行数:50,代码来源:Messages.scala


示例10: LocalCollectionUserTest

//设置package包名称以及导入依赖的类
package storage.local.collection

import java.io.File
import java.nio.file.{Files, Paths}

import play.api.libs.json.{JsResult, Json}
import storage.model.StorageModelUser

object LocalCollectionUserTest extends LocalCollection[StorageModelUser] {
  override def collectionName: String = "userTest"

  override def getBaseDirectory: Option[String] = {
    val basePath = System.getProperty("user.dir") + File.separator + "data" + File.separator + collectionName
    try {
      if (Files.exists(Paths.get(basePath))) {
        Some(basePath)
      } else {
        try {
          Files.createDirectories(Paths.get(basePath))
          Some(basePath)
        } catch {
          case e: Exception => None
        }
      }
    } catch {
      case e: Exception => None
    }
  }


  override def serialize(data: StorageModelUser): Array[Byte] = {
    Json.stringify(Json.toJson(data)).getBytes()
  }

  override def deserialize(serializedData: Array[Byte]): JsResult[StorageModelUser] = {
    Json.fromJson[StorageModelUser](Json.parse(serializedData))
  }
} 
开发者ID:kstreee,项目名称:analyzer-github-CI,代码行数:39,代码来源:LocalCollectionUserTest.scala


示例11: PingpongMatch

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

import models.player.{Player, Rank}
import models.Model
import play.api.libs.json.{JsObject, JsResult, JsValue, Json}
import utils.JsonUtils


case class PingpongMatch(
                      id: String,
                      playerA: Option[Player],
                      playerB: Option[Player],
                      roundId: String,
                      handicap: Int,
                      isHandicapForB: Boolean,
                      targetScore: Int,
                      numberOfSetsToWin: Int,
                      wonSetsA: Int,
                      wonSetsB: Int,
                      games: List[PingpongGame])

object MatchEvidence{

  implicit object matchIsModel extends Model[PingpongMatch]{
    override def getId(m: PingpongMatch): Option[String] = Some(m.id)

    override def setId(id: String)(m: PingpongMatch): PingpongMatch = m.copy(id = id)

    implicit val rankFormat = Json.format[Rank]
    implicit val playerFormat = Json.format[Player]
    val optionPlayerWrites = JsonUtils.optionWrites(playerFormat)
    implicit val gameWrites = Json.format[PingpongGame]
    override def writes(o: PingpongMatch): JsObject = Json.format[PingpongMatch].writes(o)

    override def reads(json: JsValue): JsResult[PingpongMatch] = Json.format[PingpongMatch].reads(json)
  }
}

object MatchChecker{
  def calculateSets(pingpongMatch: PingpongMatch): PingpongMatch = {
    val result = pingpongMatch.games.foldLeft[(Int, Int)]((0,0)){ (acc, game) => {
      if(game.pointA == pingpongMatch.targetScore || (game.pointA - 2 == game.pointB && game.pointA> pingpongMatch.targetScore)){
       (acc._1 + 1, acc._2)
      } else if(game.pointB == pingpongMatch.targetScore || (game.pointB - 2 == game.pointA && game.pointB> pingpongMatch.targetScore)){
        (acc._1 , acc._2 + 1)
      } else {
        acc
      }
    }}

    pingpongMatch.copy(wonSetsA = result._1, wonSetsB = result._2)
  }

  def isWon(pingpongMatch: PingpongMatch): Boolean = {
    val checkecMatch = calculateSets(pingpongMatch)
    (checkecMatch.wonSetsA > checkecMatch.wonSetsB) && checkecMatch.wonSetsA == checkecMatch.numberOfSetsToWin ||
      checkecMatch.wonSetsA < checkecMatch.wonSetsB && checkecMatch.wonSetsB == checkecMatch.numberOfSetsToWin
  }
} 
开发者ID:koenvanloock,项目名称:whifwhat,代码行数:60,代码来源:PingpongMatch.scala


示例12: TournamentSeries

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

import models.player.SeriesPlayer
import play.api.libs.json.{JsObject, JsResult, JsValue, Json}

case class TournamentSeries(
                             id: String,
                             seriesName: String,
                             seriesColor: String,
                             numberOfSetsToWin: Int,
                             setTargetScore: Int,
                             playingWithHandicaps: Boolean,
                             extraHandicapForRecs: Int,
                             showReferees: Boolean,
                             currentRoundNr: Int=1,
                             tournamentId: String)
  object SeriesEvidence {

    implicit object seriesIsModel extends Model[TournamentSeries] {
      override def getId(m: TournamentSeries): Option[String] = Some(m.id)

      override def setId(id: String)(m: TournamentSeries): TournamentSeries = m.copy(id = id)

      override def writes(o: TournamentSeries): JsObject = Json.format[TournamentSeries].writes(o)

      override def reads(json: JsValue): JsResult[TournamentSeries] = Json.format[TournamentSeries].reads(json)
    }

  }

case class SeriesWithPlayers(seriesId: String,
                             seriesName: String,
                             seriesColor: String,
                             numberOfSetsToWin: Int,
                             setTargetScore: Int,
                             playingWithHandicaps: Boolean,
                             extraHandicapForRecs: Int,
                             showReferees: Boolean,
                             currentRoundNr: Int=1,
                             seriesPlayers: List[SeriesPlayer],
                             tournamentId: String) 
开发者ID:koenvanloock,项目名称:whifwhat,代码行数:42,代码来源:TournamentSeries.scala


示例13: SequenceField

//设置package包名称以及导入依赖的类
package io.really.model

import _root_.io.really.ReallyGlobals
import play.api.libs.json.{ JsObject, JsResult, JsValue, JsPath }

case class SequenceField[T](
    key: FieldKey,
    dataType: DataType[T],
    validationExpression: Option[JsScript],
    default: Option[JsScript],
    required: Boolean
)(implicit val globals: ReallyGlobals) extends ActiveField[T] {
  override def read(root: JsPath, in: JsObject): JsResult[JsObject] = ???

  def runThroughValidator(path: JsPath, in: JsValue): JsResult[JsObject] = ???

  protected def readDefault(path: JsPath): JsResult[JsValue] = ???

} 
开发者ID:radiodb,项目名称:radiodb,代码行数:20,代码来源:SequenceField.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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