本文整理汇总了Scala中play.api.libs.json.JsNumber类的典型用法代码示例。如果您正苦于以下问题:Scala JsNumber类的具体用法?Scala JsNumber怎么用?Scala JsNumber使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了JsNumber类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: 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)
示例2: JsonResultFormatSpec
//设置package包名称以及导入依赖的类
package com.pygmalios.reactiveinflux.command.query
import org.junit.runner.RunWith
import org.scalatest.FlatSpec
import org.scalatest.junit.JUnitRunner
import play.api.libs.json.{JsNumber, JsString, Json}
@RunWith(classOf[JUnitRunner])
class JsonResultFormatSpec extends FlatSpec {
import JsonResultFormatSpec._
import JsonResultFormat._
behavior of "format"
it should "parse result with one series" in {
// Execute
val jsonResult = Json.parse(example1).as[JsonResult]
assert(jsonResult.series.size == 1)
val series = jsonResult.series.head
assert(series.name == "cpu_load_short")
assert(series.columns == List("time", "value"))
assert(series.values.size == 3)
assert(series.values(0)(0) == JsString("2015-01-29T21:55:43.702900257Z"))
assert(series.values(0)(1) == JsNumber(0.55))
assert(series.values(1)(0) == JsString("2015-01-29T21:55:43.702900257Z"))
assert(series.values(1)(1) == JsNumber(23422))
assert(series.values(2)(0) == JsString("2015-06-11T20:46:02Z"))
assert(series.values(2)(1) == JsNumber(0.64))
}
}
object JsonResultFormatSpec {
val example1 = """
|{
| "series": [
| {
| "name": "cpu_load_short",
| "columns": [
| "time",
| "value"
| ],
| "values": [
| [
| "2015-01-29T21:55:43.702900257Z",
| 0.55
| ],
| [
| "2015-01-29T21:55:43.702900257Z",
| 23422
| ],
| [
| "2015-06-11T20:46:02Z",
| 0.64
| ]
| ]
| }
| ]
| }
""".stripMargin
}
示例3: ShapelessCoproductJsonSpec
//设置package包名称以及导入依赖的类
package microtools.shapeless
import org.scalatest.MustMatchers
import org.scalatestplus.play.PlaySpec
import play.api.libs.json.{JsBoolean, JsNumber, JsString, Json}
import shapeless._
class ShapelessCoproductJsonSpec extends PlaySpec with MustMatchers {
import ShapelessCoproductJson._
"Shapeless writes" should {
"serialize a simple coproduct" in {
type ISB = Int :+: String :+: Boolean :+: CNil
val isb1 = Coproduct[ISB](1234)
val isb2 = Coproduct[ISB]("string")
val isb3 = Coproduct[ISB](true)
Json.toJson(isb1) mustBe JsNumber(1234)
Json.toJson(isb2) mustBe JsString("string")
Json.toJson(isb3) mustBe JsBoolean(true)
}
}
"Shapeless reads" should {
"deserialize a simple coproduct" in {
type ISB = Int :+: String :+: Boolean :+: CNil
val isb1 = JsBoolean(true).as[ISB]
val isb2 = JsString("string").as[ISB]
val isb3 = JsNumber(1234).as[ISB]
isb1.select[Boolean] mustBe Some(true)
isb2.select[String] mustBe Some("string")
isb3.select[Int] mustBe Some(1234)
}
}
}
示例4: Holiday
//设置package包名称以及导入依赖的类
package com.github.yandoroshenko.workhourscounter
import java.time.LocalDate
import play.api.libs.json.{JsArray, JsNumber, Json}
import scala.util.{Failure, Success, Try}
trait HolidayCalendar extends Calendar {
case class Holiday(date: LocalDate, name: String)
private val url: String = "http://kayaposoft.com/enrico/json/v1.0/?action=getPublicHolidaysForMonth&month=%s&year=%s&country=%s"
def getHolidays(from: LocalDate, to: LocalDate, countryCode: String): Either[Throwable, Set[Holiday]] =
Try(getDays(from, to)
.map(_.withDayOfMonth(1))
.distinct
.map(d =>
Json.parse(io.Source.fromURL(String.format(url, d.getMonthValue.toString, d.getYear.toString, countryCode)).mkString)
.as[JsArray].value
.map(v => v \ "date" -> v \ "localName")
.map(v => Holiday(
LocalDate.of(
(v._1 \ "year").as[JsNumber].value.toIntExact,
(v._1 \ "month").as[JsNumber].value.toIntExact,
(v._1 \ "day").as[JsNumber].value.toInt),
v._2.as[String])))) match {
case Success(a) => Right(a.reduceLeft(_ ++ _).toSet)
case Failure(e) => Left(e)
}
}
示例5: TestData
//设置package包名称以及导入依赖的类
package controllers
import models.database.ReportEntity
import play.api.libs.json.{JsNumber, Json, JsString, JsArray}
import org.joda.time.LocalDate
object TestData {
val inputData = Seq(
ReportEntity("de1", new LocalDate("2014-07-01"), 10, 4, 1),
ReportEntity("de1", new LocalDate("2014-07-02"), 12, 2, 0),
ReportEntity("en2", new LocalDate("2014-07-03"), 8, 1, 1),
ReportEntity("en2", new LocalDate("2014-07-04"), 14, 5, 3),
ReportEntity("ua", new LocalDate("2014-07-05"), 10, 3, 2),
ReportEntity("ru", new LocalDate("2014-07-06"), 4, 0, 0),
ReportEntity("dk", new LocalDate("2014-07-07"), 2, 2, 1))
val expectedWorldsList = JsArray(Seq(JsString("de1"), JsString("dk"), JsString("en2"), JsString("ru"), JsString("ua")))
val expectedReportsAll = Json.obj(
"rows" -> JsArray(Seq(
Json.obj("world" -> "dk", "date" -> "2014-07-07", "detected" -> 2, "banned" -> 2, "deleted" -> 1),
Json.obj("world" -> "ru", "date" -> "2014-07-06", "detected" -> 4, "banned" -> 0, "deleted" -> 0),
Json.obj("world" -> "ua", "date" -> "2014-07-05", "detected" -> 10, "banned" -> 3, "deleted" -> 2),
Json.obj("world" -> "en2", "date" -> "2014-07-04", "detected" -> 14, "banned" -> 5, "deleted" -> 3),
Json.obj("world" -> "en2", "date" -> "2014-07-03", "detected" -> 8, "banned" -> 1, "deleted" -> 1),
Json.obj("world" -> "de1", "date" -> "2014-07-02", "detected" -> 12, "banned" -> 2, "deleted" -> 0),
Json.obj("world" -> "de1", "date" -> "2014-07-01", "detected" -> 10, "banned" -> 4, "deleted" -> 1)
)),
"totalRows" -> JsNumber(7),
"totalDetected" -> JsNumber(60),
"totalBanned" -> JsNumber(17),
"totalDeleted" -> JsNumber(8))
val expectedReportsWithDateAndSort = Json.obj(
"rows" -> JsArray(Seq(
Json.obj("world" -> "en2", "date" -> "2014-07-03", "detected" -> 8, "banned" -> 1, "deleted" -> 1),
Json.obj("world" -> "de1", "date" -> "2014-07-02", "detected" -> 12, "banned" -> 2, "deleted" -> 0),
Json.obj("world" -> "en2", "date" -> "2014-07-04", "detected" -> 14, "banned" -> 5, "deleted" -> 3)
)),
"totalRows" -> JsNumber(3),
"totalDetected" -> JsNumber(34),
"totalBanned" -> JsNumber(8),
"totalDeleted" -> JsNumber(4))
val expectedReportsWithWorld = Json.obj(
"rows" -> JsArray(Seq(Json.obj("world" -> "ua", "date" -> "2014-07-05", "detected" -> 10, "banned" -> 3, "deleted" -> 2))),
"totalRows" -> JsNumber(1),
"totalDetected" -> JsNumber(10),
"totalBanned" -> JsNumber(3),
"totalDeleted" -> JsNumber(2))
}
示例6: LocationsServlet
//设置package包名称以及导入依赖的类
package io.foxtrot.mapeador.servlets
import io.foxtrot.mapeador.math.DistanceCalculator
import io.foxtrot.mapeador.math.clustering.DBSCAN
import io.foxtrot.mapeador.models.{TimestampedLocationsClusterFactory, Location, MapRange, TimestampedLocation}
import org.scalatra.scalate.ScalateSupport
import org.scalatra.{Params, ScalatraServlet}
import org.slf4j.LoggerFactory
import play.api.libs.json.{JsArray, JsNumber, Json}
class LocationsServlet(locations: Map[String, Seq[TimestampedLocation]]) extends ScalatraServlet with ScalateSupport {
private val logger = LoggerFactory.getLogger(this.getClass)
get("/") {
contentType = "text/html"
ssp("/index")
}
get("/locations") {
contentType = "application/json"
val mapRange = getMapRange(params).getOrElse(MapRange.world)
Json.toJson(locations.par.map {
case (key: String, locs: Seq[TimestampedLocation]) =>
val rangeLocations = locs.filter(l => isInRange(l, mapRange))
val clustered = if (rangeLocations.size > 1000) {
DBSCAN(getClusteringMeters(mapRange), 1, includeOutliers = true, new TimestampedLocationsClusterFactory).cluster(rangeLocations).map(_.getCentroid)
} else {
rangeLocations
}
key -> JsArray(clustered.map {
case l: TimestampedLocation =>
JsArray(Seq(JsNumber(l.location.latitude), JsNumber(l.location.longitude)))
}.toList)
}.seq)
}
private def getMapRange(params: Params): Option[MapRange] = {
for {
northeast <- params.get("northeast")
southwest <- params.get("southwest")
neLatitude <- northeast.split(",").headOption
neLongitude <- northeast.split(",").lastOption
swLatitude <- southwest.split(",").headOption
swLongitude <- southwest.split(",").lastOption
} yield MapRange(Location(neLatitude.toDouble, neLongitude.toDouble), Location(swLatitude.toDouble, swLongitude.toDouble))
}
private def isInRange(timestampedLocation: TimestampedLocation, mapRange: MapRange): Boolean = {
timestampedLocation.location.latitude < mapRange.northeast.latitude &&
timestampedLocation.location.latitude > mapRange.southwest.latitude &&
timestampedLocation.location.longitude < mapRange.northeast.longitude &&
timestampedLocation.location.longitude > mapRange.southwest.longitude
}
private def getClusteringMeters(mapRange: MapRange): Double = {
Math.min(DistanceCalculator.vincentyDistance(mapRange.northeast, mapRange.southwest) / 300.0, 50000)
}
}
示例7: FacebookFeed
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.{Inject, Singleton}
import controllers.NeedLogin.OptAuthenticated
import helpers.{Cache, Facebook, FacebookRepo}
import play.api.mvc._
import play.api.libs.json.{JsNumber, JsObject, JsString, Json}
import play.api.Configuration
@Singleton
class FacebookFeed @Inject() (
cc: MessagesControllerComponents,
cache: Cache,
facebookRepo: FacebookRepo,
conf: Configuration,
optAuthenticated: OptAuthenticated
) extends MessagesAbstractController(cc) {
val facebook: () => Facebook = cache.cacheOnProd(
() => facebookRepo(
conf.get[String]("facebook.appId"),
conf.get[String]("facebook.appSecret")
)
)
def latestPostId(pageId: String) = optAuthenticated { implicit request: MessagesRequest[AnyContent] =>
facebook().feedsV25(pageId).headOption.map {
feed => (feed.postId.toString, feed.createdTime)
} match {
case None => NotFound("No feed for page '" + pageId + "' found.")
case Some(t) => Ok(
Json.toJson(
JsObject(
Seq(
"postId" -> JsString(t._1),
// 64bit double float has 52 bit width fraction.
// 2^52 / 1000 / 60 / 60 / 24 / 365 = 142808.207362.
// For about 142,808 years since epoch, there should be
// no error to conver long to double float.
"lastUpdate" -> JsNumber(t._2.getEpochSecond)
)
)
)
)
}
}
}
示例8: UserControllerSpec
//设置package包名称以及导入依赖的类
package eitherexercice.exo
import org.scalatest._
import play.api.libs.json.{JsArray, JsNumber}
class UserControllerSpec extends FlatSpec
with GivenWhenThen
with EitherValues
with Matchers {
behavior of "UserController"
it should "fail when it cannot parse the json" in {
Given("A malformed json")
val json = JsArray(Seq(JsNumber(1)))
When("We ask to save the user")
val triedUser = DefaultUserController.save(json)
Then("The result is a failure")
triedUser.left.value should be(a[MalformedUserPayload])
}
}
示例9: UserControllerSpec
//设置package包名称以及导入依赖的类
package tryexercice.exo
import org.scalatest._
import play.api.libs.json.{JsArray, JsNumber}
class UserControllerSpec extends FlatSpec
with GivenWhenThen
with TryValues
with Matchers {
behavior of "UserController"
it should "fail when it cannot parse the json" in {
Given("A malformed json")
val json = JsArray(Seq(JsNumber(1)))
When("We ask to save the user")
val triedUser = DefaultUserController.save(json)
Then("The result is a failure")
triedUser should be(a[MalformedUserPayload])
}
}
示例10: SecurityServices
//设置package包名称以及导入依赖的类
package services
import javax.inject._
import play.modules.reactivemongo.ReactiveMongoApi
import scala.concurrent.{Future, ExecutionContext}
import reactivemongo.play.json.collection.JSONCollection
import play.api.libs.json.{JsNumber, Json, JsArray}
import utils.Constants
class SecurityServices @Inject()(val reactiveMongoApi: ReactiveMongoApi,constant:Constants)(implicit exec: ExecutionContext) {
def static_data: Future[JSONCollection] = reactiveMongoApi.database.map(_.collection[JSONCollection]("static-data"))
def getAroundCrimes(lat:Double,lng:Double) = {
for {
crimesCol <- static_data
crimes_count <- crimesCol.count(Some(
Json.obj(
"type" -> constant.DATA_SECURITY,
"subtype" -> constant.DATA_CRIMES,
"geometry" -> Json.obj(
"$near" -> Json.obj(
"$geometry" -> Json.obj("type" -> "Point", "coordinates" -> JsArray(Seq(JsNumber(lat),JsNumber(lng)))),
"$maxDistance" -> 1000
)
)))
)
} yield {
crimes_count
}
}
}
示例11: HomeController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject._
import com.evojam.play.elastic4s.PlayElasticFactory
import com.evojam.play.elastic4s.configuration.ClusterSetup
import play.api.mvc._
import models._
import play.api.Play.current
import play.api.i18n.Messages.Implicits._
import play.api.libs.json.JsNumber
import scala.concurrent.{ExecutionContext, Future}
import scala.util.Try
import play.api.Logger
import play.api.Configuration
import play.api.cache.CacheApi
import play.api.i18n.Messages
@Singleton
class HomeController @Inject()(cs: ClusterSetup, ef: PlayElasticFactory)(implicit exec: ExecutionContext) extends ApplicationController(ef: PlayElasticFactory, cs: ClusterSetup) {
def index(label: String) = Action.async { implicit request =>
var query:Map[String, Object] = Map("size" -> JsNumber(50), "sort" -> Map("updated_timestamp" -> "desc"))
val label_name = Trip.labels.get(label)
if(label_name != None) {
Logger.debug(s"yeah $label_name")
query += "filter" -> Map("labels" -> label_name.get)
Logger.debug(query.toString())
}
Try(Trip.browse(client, query)).toOption match {
case Some(trips) => trips.map(t => Ok(views.html.index(t)))
case None => Future { Ok(views.html.index(List())) }
}
}
}
示例12: MarketPrice
//设置package包名称以及导入依赖的类
package com.kylegalloway.evescala.crest.model
import play.api.libs.json.{JsNumber, JsValue}
object MarketPrice {
def fromJson(json: JsValue): MarketPrice = {
val adjustedPrice = (json \ "adjustedPrice").getOrElse(JsNumber(0.0)).as[Double]
val averagePrice = (json \ "averagePrice").getOrElse(JsNumber(0.0)).as[Double]
val typeID = (json \ "type" \ "id").as[Int]
MarketPrice(
typeID = typeID,
adjustedPrice = adjustedPrice,
averagePrice = averagePrice
)
}
}
case class MarketPrice(
typeID: Int,
adjustedPrice: Double,
averagePrice: Double
)
示例13: MoneyFormatSpec
//设置package包名称以及导入依赖的类
package boldradius.squants.json
import com.typesafe.scalalogging.LazyLogging
import org.scalatest.{Matchers, WordSpec}
import play.api.libs.json.Json._
import play.api.libs.json.{JsError, JsNumber, JsString, JsSuccess}
import squants.Money
import squants.market.{BTC, JPY, USD, XAU}
class MoneyFormatSpec
extends WordSpec
with Matchers
with LazyLogging {
"JSON serializers" should {
val exemplars =
USD(10) ::
JPY(1200) ::
XAU(50) ::
BTC(50) ::
Nil
exemplars foreach { expected =>
s"""read and write "$expected" without loss""" in {
val actual = toJson(expected).validate[Money]
actual should be(JsSuccess(expected))
}
}
"report invalid serializations" in {
JsString("bogus money").validate[Money] should be(a[JsError])
}
"report invalid types" in {
JsNumber(123).validate[Money] should be(a[JsError])
}
}
}