当前位置: 首页>>代码示例>>Scala>>正文


Scala Json类代码示例

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


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

示例1: HomeController

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

import javax.inject._

import org.slf4j.LoggerFactory
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.{JsObject, JsValue, Json}
import play.api.mvc._
import play.modules.reactivemongo._
import play.modules.reactivemongo.json._
import play.modules.reactivemongo.json.collection.{JSONCollection, _}
import reactivemongo.api.Cursor

import scala.concurrent.Future

@Singleton
class HomeController  @Inject() (val reactiveMongoApi: ReactiveMongoApi)
  extends Controller with MongoController with ReactiveMongoComponents {

  val logger = LoggerFactory.getLogger(this.getClass)

  def collection: JSONCollection = db.collection[JSONCollection]("scrawler1")

  def index = Action {
    Ok(views.html.index(""))
  }

  def query = Action.async { request =>
    val body = request.body
    val query = body.asFormUrlEncoded.get("query")

    val querySet = query.toSet[String]

    val keywords = querySet.flatMap({ string: String =>
      string.split(" ")
    })

    val searchQuery = Json.obj("keywords" -> Json.obj("$in" -> Json.toJson(keywords)))
    logger.info(s"Internal query from client: $searchQuery")
    val cursor: Cursor[JsObject] = collection.find(searchQuery).cursor[JsObject]

    val result: Future[List[JsObject]] = cursor.collect[List]()

    val resultJson: Future[JsValue] =
      result.map { persons => Json.toJson(persons) }

    resultJson.map { results =>
      val title = results \\ "title"
      val url = results \\ "url"
      val description = results \\ "body"
      val queryData: Seq[((JsValue, JsValue), JsValue)] = title.zip(url).zip(description)
      Ok(views.html.result(queryData))
    }
  }
} 
开发者ID:slideon,项目名称:Scrawler-frontend,代码行数:56,代码来源:HomeController.scala

示例2: VersionController

//设置package包名称以及导入依赖的类
package controllers
import git.GitInfo
import play.api.libs.json.Json
import play.api.mvc.{Action, Controller}

class VersionController extends Controller {


  def index = Action {
    Ok(
      Json.obj(
        "lastCommit" -> Json.obj(
          "branch" -> GitInfo.currentBranch(),
          "message" -> GitInfo.lastRevCommitMessage(),
          "author" -> GitInfo.lastRevCommitAuthor(),
          "hash" -> GitInfo.lastRevCommitName(),
          "date" -> GitInfo.lastRevCommitTime()
        ))
    )
  }

} 
开发者ID:dgouyette,项目名称:git-info,代码行数:23,代码来源:VersionController.scala

示例3: GeoTagSpec

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

import java.util.UUID
import org.joda.time.{ DateTime, DateTimeZone }
import org.joda.time.format.DateTimeFormat
import org.specs2.mutable._
import org.specs2.runner._
import org.junit.runner._
import play.api.libs.json.Json
import play.api.test._
import play.api.test.Helpers._
import scala.io.Source

@RunWith(classOf[JUnitRunner])
class GeoTagSpec extends Specification {
  
  private val DATE_TIME_PATTERN = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ")

  "The sample geotag" should {
    
    "be properly created from JSON" in {
      val json = Source.fromFile("test/resources/models/geotag/geotag.json").getLines().mkString("\n")
      val result = Json.fromJson[GeoTag](Json.parse(json))
      
      // Parsed without errors?
      result.isSuccess must equalTo(true) 
      
      val geotag = result.get
      geotag.annotationId must equalTo(UUID.fromString("5c25d207-11a5-49f0-b2a7-61a6ae63d96c"))
      geotag.documentId must equalTo("qhljvnxnuuc9i0")
      geotag.filepartId must equalTo(UUID.fromString("f903b736-cae8-4fe3-9bda-01583783548b"))
      geotag.gazetteerUri must equalTo("http://pleiades.stoa.org/places/118543")
      geotag.lastModifiedAt must equalTo(DateTime.parse("2016-09-19T13:09:00Z", DATE_TIME_PATTERN).withZone(DateTimeZone.UTC))
    }
    
  }
  
  "JSON serialization/parsing roundtrip" should {
    
    "yield an equal geotag" in {
      val geotag = GeoTag(
        UUID.randomUUID(),
        "qhljvnxnuuc9i0",
        UUID.fromString("841f9462-beb0-4967-ad48-64af323fc4c1"),
        "http://pleiades.stoa.org/places/118543",
        Seq.empty[String], // toponym
        Seq.empty[String], // contributors
        None, // lastModifiedBy
        DateTime.parse("2016-02-23T18:24:00Z", DATE_TIME_PATTERN).withZone(DateTimeZone.UTC))
        
      // Convert to JSON
      val serialized = Json.prettyPrint(Json.toJson(geotag))
      
      val parseResult = Json.fromJson[GeoTag](Json.parse(serialized))
      parseResult.isSuccess must equalTo(true)
      parseResult.get must equalTo(geotag)
    }
    
  }
  
} 
开发者ID:pelagios,项目名称:recogito2,代码行数:62,代码来源:GeoTagSpec.scala

示例4: MenuPerDayPerPersonForm

//设置package包名称以及导入依赖的类
package lunatech.lunchplanner.viewModels

import java.util.UUID

import play.api.data.Form
import play.api.data.Forms.{ mapping, text, _ }
import play.api.data.format.Formats._
import play.api.libs.json.{ Json, OFormat }

case class MenuPerDayPerPersonForm(
  menuPerDayUuid: List[UUID],
  menuDate: List[String]
)

object MenuPerDayPerPersonForm {
  implicit val menuPerDayPerPersonFormFormat: OFormat[MenuPerDayPerPersonForm] = Json.format[MenuPerDayPerPersonForm]

  val menuPerDayPerPersonForm = Form(
    mapping(
      "menuPerDayUuid" -> list(of[UUID]),
      "menuDate" -> list(text)
    )(MenuPerDayPerPersonForm.apply)(MenuPerDayPerPersonForm.unapply)
  )
} 
开发者ID:lunatech-labs,项目名称:lunatech-lunch-planner,代码行数:25,代码来源:MenuPerDayPerPersonForm.scala

示例5: MongoSpec

//设置package包名称以及导入依赖的类
import com.fasterxml.jackson.annotation.JsonValue
import org.scalatestplus.play.PlaySpec
import play.api.test._
import play.modules.reactivemongo._
import services._
import connectors._
import play.api.libs.json.{JsValue, Json}
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import play.api.test.Helpers._

class MongoSpec extends PlaySpec {

  val mongo = new MongoExecutor(new MyMongoConnection)

  "mongo" should {
    val document = BSONDocument(
      "_id" -> BSONObjectID.parse("5951aa22c8e144a1c7e2b9dc").get,
      "name" -> "mongoTest",
      "requests" -> 0,
      "userErrors" -> 0
    )

    "return a BSON document" in {
      val result = await(mongo.getController("mongoTest"))
      result mustBe Some(document)
      result match {
        case Some(document) => document.getAs[Int]("requests").map(x => x mustBe 0)
        case None => throw fail("No document found")
      }
    }
  }
} 
开发者ID:ZDevelop94,项目名称:ZolvedIT,代码行数:35,代码来源:MongoSpec.scala

示例6: ArtistController

//设置package包名称以及导入依赖的类
package controllers
import javax.inject._
import model.Artist
import play.api.mvc._
import play.api.libs.json.Json
import services.{ArtistServices}
import play.api.Logger

@Singleton
class ArtistController @Inject() (service : ArtistServices) extends Controller {

  def getArtist(name: String) = Action {
    val response = service.findAllByType(name)
    Logger.debug("Attempting risky calculation.")
    Ok(Json.toJson(response))

  }

  def addArtist = Action { request =>
    val json = request.body.asJson.get
    val stock = Json.fromJson[Artist](json)
    println(stock)
    stock.isSuccess match {
      case true => {
        service.add(stock.get);
        Ok("The Artist has been added !!!")
      }
      case _ => Ok("The Artist Didnt get Added!!")
    }
  }
} 
开发者ID:ralekar,项目名称:play-scala-casbah,代码行数:32,代码来源:ArtistController.scala

示例7: PullRequestSpec

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

import models.PullRequest
import org.scalatestplus.play._
import play.api.libs.json.{Json, JsValue, JsPath}
import play.api.libs.json._

import scalaz.\/-

import play.api.libs.json._

class PullRequestSpec extends PlaySpec {

  "PullRequest" must {
    "buildFrom" when {
      "inputs are valid" in {

        val json: JsValue = Json.parse("""
{
  "issue": {
    "number": 12
  },
  "repository": {
    "owner":{
      "login": "Mirek"
    },
    "name": "Wohoo"
  }
}""")

       PullRequest.buildFrom(json) mustBe \/-(PullRequest(12, "Mirek", "Wohoo"))
      }
    }

  }
} 
开发者ID:MiroslavCsonka,项目名称:u-cant-merge-this,代码行数:37,代码来源:PullRequestSpec.scala

示例8: PullRequestSampleClient

//设置package包名称以及导入依赖的类
package de.stema.pullrequests.client

import java.io.{File, FileInputStream}
import javax.inject.Inject

import de.stema.pullrequests.dto.{ProjectDTO, PullRequestDTO}
import de.stema.util.JsonObjectMapper
import play.api.libs.json.Json

import scala.concurrent.Future


class PullRequestSampleClient @Inject()(jsonObjectMapper: JsonObjectMapper
                                       ) extends PullRequestClient {

  def getPullRequests(configuration: String): Seq[Future[ProjectDTO]] = {
    val jsonFile = new File("conf/testcontent.json")

    val stream = new FileInputStream(jsonFile)
    val json = try {
      Json.parse(stream)
    } finally {
      stream.close()
    }
    val prs = jsonObjectMapper.getInstances[PullRequestDTO](json.toString())
    Seq(Future.successful(ProjectDTO("testProject", prs)))
  }
} 
开发者ID:callidustaurus,项目名称:github-api,代码行数:29,代码来源:PullRequestSampleClient.scala

示例9: ClientRecord

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

import com.google.inject.Inject
import play.api.db.slick.DatabaseConfigProvider
import play.api.libs.json.Json
import slick.driver.JdbcProfile


case class ClientRecord(id: Int, firstName: String, lastName: String, petId: Int)
object ClientRecord {
  implicit val clientRecordFormat = Json.format[ClientRecord]
}

class ClientsRepo @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) {
  val dbConfig = dbConfigProvider.get[JdbcProfile]
  val db       = dbConfig.db

  import dbConfig.driver.api._
  val clients = TableQuery[ClientsTable]

  class ClientsTable(tag: Tag) extends Table[ClientRecord](tag, "CLIENTS") {

    def id = column[Int]("ID", O.AutoInc, O.PrimaryKey)
    def firstName = column[String]("FIRST_NAME")
    def lastName = column[String]("LAST_NAME")
    def petId = column[Int]("PET_ID")

    def * = (id, firstName, lastName, petId) <> ((ClientRecord.apply _).tupled, ClientRecord.unapply)
  }
} 
开发者ID:microservicesinaction,项目名称:playProject,代码行数:31,代码来源:Clients.scala

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

示例11: 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
    )
  }
} 
开发者ID:helde,项目名称:GitHubRepositoriesActivities,代码行数:29,代码来源:WSGitHubCommit.scala

示例12: WebSocketActor

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

import akka.actor._
import com.inspiringsolutions.tweet.core.Global
import com.inspiringsolutions.tweet.models.{SimplifiedTweet, Tweet}
import play.api.libs.json.Json

object WebSocketActor {
  def props(out: ActorRef, keyword: Option[String]) = Props(new WebSocketActor(out, Global.webSocketCoordinator, keyword))
}

class WebSocketActor (out: ActorRef, coordinator: ActorRef, keyword: Option[String]) extends Actor {

  def receive = {
    case tweet: Tweet =>
      out ! Json.toJson(SimplifiedTweet(tweet.id_str, tweet.text, tweet.user.name, tweet.user.profile_image_url)).toString()
  }

  override def preStart() {
    coordinator ! RegisterSocketActor(keyword)
  }

  override def postStop() {
    coordinator ! UnregisterSocketActor
  }

} 
开发者ID:gitter-badger,项目名称:inspiring-tooling,代码行数:28,代码来源:WebSocketActor.scala

示例13: PreprocessedFromStringUnmarshaller

//设置package包名称以及导入依赖的类
package akka.http.documenteddsl

import akka.http.scaladsl.marshallers.playjson.PlayJsonSupport.PlayJsonError
import akka.http.scaladsl.model.MediaTypes.`application/json`
import akka.http.scaladsl.server.{RejectionError, ValidationRejection}
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, FromStringUnmarshaller, Unmarshaller}
import akka.util.ByteString
import play.api.libs.json.{JsError, JsValue, Json, Reads}

class PreprocessedFromStringUnmarshaller[T](sanitize: Preprocess[String], _fsu: FromStringUnmarshaller[T]) {
  implicit val fsu: FromStringUnmarshaller[T] = Unmarshaller withMaterializer {
    implicit ec =>
      implicit mat =>
        string =>
          _fsu(sanitize(string))
  }
}

object PreprocessedFromStringUnmarshaller {
  implicit def unmarshaller[T](implicit sanitize: Preprocess[String] = Preprocess.identity, fsu: FromStringUnmarshaller[T]): PreprocessedFromStringUnmarshaller[T] = {
    new PreprocessedFromStringUnmarshaller(sanitize, fsu)
  }
}

class PreprocessedFromEntityUnmarshaller[T](sanitize: Preprocess[JsValue], reads: Reads[T]) {
  private val jsonStringUnmarshaller =
    Unmarshaller.byteStringUnmarshaller
      .forContentTypes(`application/json`)
      .mapWithCharset {
        case (ByteString.empty, _) => throw Unmarshaller.NoContentException
        case (data, charset)       => data.decodeString(charset.nioCharset.name)
      }

  implicit val fsu: FromEntityUnmarshaller[T] = jsonStringUnmarshaller map { data =>
    val json = sanitize(Json parse data)

    reads reads json recoverTotal { error =>
      throw RejectionError(ValidationRejection(JsError.toJson(error).toString, Some(PlayJsonError(error))))
    }
  }
}

object PreprocessedFromEntityUnmarshaller {
  implicit def unmarshaller[T](implicit sanitize: Preprocess[JsValue] = Preprocess.identity, reads: Reads[T]): PreprocessedFromEntityUnmarshaller[T] = {
    new PreprocessedFromEntityUnmarshaller(sanitize, reads)
  }
}

trait Preprocess[T] {
  def apply(x: T): T
}
object Preprocess {
  def identity[T]: Preprocess[T] = new Preprocess[T] {
    override def apply(x: T): T = x
  }
} 
开发者ID:evolution-gaming,项目名称:akka-http-documenteddsl,代码行数:57,代码来源:Preprocess.scala

示例14: JsonSchema

//设置package包名称以及导入依赖的类
package akka.http.documenteddsl.documentation

import org.coursera.autoschema.{AutoSchema, TypeMappings}
import play.api.libs.json.{JsObject, Json}

import scala.reflect.runtime.{universe => ru}
import scala.util.control.NonFatal

object JsonSchema {

  def resolveSchema[T](implicit t: ru.TypeTag[T], as: AutoSchema): JsObject = {
    try as.createSchema[T] catch {
      case NonFatal(err) =>
        def errPath(ex: Throwable): String = ex.getCause match {
          case null => ex.getMessage
          case x    => "[" + ex.getClass.getSimpleName + "]" + ex.getMessage + ". Caused by: " + errPath(x)
        }
        Json.obj("error" -> s"$t: ${errPath(err)}")
    }
  }

  val string: JsObject    = Json.obj("type" -> "string")
  val numeric: JsObject   = Json.obj("type" -> "number", "format" -> "number")
  val boolean: JsObject   = Json.obj("type" -> "boolean")
}

trait DocumentedTypeMappings extends TypeMappings {
  import JsonSchema._

  override def schemaTypeForScala(typeName: String): Option[JsObject] = {
    schemaTypes.get(typeName)
  }

  private val schemaTypes = Map(
    "scala.Nothing"           -> Json.obj(),
    "scala.Unit"              -> Json.obj(),
    "org.joda.time.DateTime"  -> Json.obj("type" -> "string", "format" -> "date"),
    "java.time.ZonedDateTime" -> Json.obj("type" -> "string", "format" -> "date"),
    "java.time.LocalDate"     -> Json.obj("type" -> "string", "format" -> "date", "pattern" -> localDatePattern),
    "java.util.Date"          -> Json.obj("type" -> "string", "format" -> "date"),
    "java.lang.String"        -> string,
    "scala.Boolean"           -> boolean,
    "scala.Int"               -> numeric,
    "scala.Long"              -> numeric,
    "scala.Double"            -> numeric,
    "scala.math.BigInt"       -> numeric,
    "scala.math.BigDecimal"   -> numeric,
    "java.util.UUID"          -> Json.obj("type" -> "string", "pattern" -> "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$")
  )

  lazy val localDatePattern = "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
}

object DocumentedTypeMappings extends DocumentedTypeMappings 
开发者ID:evolution-gaming,项目名称:akka-http-documenteddsl,代码行数:55,代码来源:JsonSchema.scala

示例15: SaveNewMessage

//设置package包名称以及导入依赖的类
package sample.helloworldconsumer.impl

import com.lightbend.lagom.scaladsl.persistence.PersistentEntity.ReplyType
import play.api.libs.json.Json
import akka.Done
import com.lightbend.lagom.scaladsl.playjson.{JsonSerializer, JsonSerializerRegistry}

import scala.collection.immutable.Seq


sealed trait MessageCommand [T] extends ReplyType[T]

case class SaveNewMessage(message: String) extends MessageCommand[Done]

object SaveNewMessage {
  implicit val formatter = Json.format[SaveNewMessage]
}

object HelloConsumerSerializerRegistry extends JsonSerializerRegistry {
  override def serializers: Seq[JsonSerializer[_]] = Seq(
    JsonSerializer[SaveNewMessage],
    JsonSerializer[MessageSaved],
    JsonSerializer[MessageState]
  )
} 
开发者ID:knoldus,项目名称:lagom-scala-wordcount.g8,代码行数:26,代码来源:MessageCommand.scala


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