本文整理汇总了Scala中scala.scalajs.js.JSON类的典型用法代码示例。如果您正苦于以下问题:Scala JSON类的具体用法?Scala JSON怎么用?Scala JSON使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了JSON类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: IndexApp
//设置package包名称以及导入依赖的类
package com.kindone.infinitewall
import com.kindone.infinitewall.persistence.api.Persistence
import com.kindone.infinitewall.persistence.localstorage.{ LocalPersistence, WallManager, LocalStorage }
import com.kindone.infinitewall.persistence.httpstorage.HttpPersistence
import com.kindone.infinitewall.persistence.wsstorage.WebSocketPersistence
import upickle.default._
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation.JSExport
import scala.scalajs.js
import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue
@JSExport
class IndexApp(val useLocalStorage: Boolean = true, val useWS: Boolean = false) {
val persistence: Persistence = {
if (useLocalStorage)
new LocalPersistence()
else if (useWS)
new WebSocketPersistence("")
else
new HttpPersistence("")
}
@JSExport
def walls(onComplete: js.Function1[js.Array[js.Dictionary[Any]], Unit]): Unit = {
import js.JSConverters._
val wallManager = persistence.wallManager
val wallsFuture = wallManager.getWalls().map { walls =>
walls.map { wall =>
JSON.parse(write(wall)).asInstanceOf[js.Dictionary[Any]]
}.toJSArray
}
wallsFuture.foreach { walls =>
onComplete.apply(walls)
}
}
@JSExport
def createWall(title: String, onComplete: js.Function1[js.Dictionary[Any], Unit]): Unit = {
val wallManager = persistence.wallManager
val wallFuture = wallManager.create(title)
wallFuture.foreach { wall =>
val result = JSON.parse(write(wall)).asInstanceOf[js.Dictionary[Any]]
onComplete.apply(result)
}
}
@JSExport
def deleteWall(id: Int, onComplete: js.Function1[Boolean, Unit]): Unit = {
val wallManager = persistence.wallManager
wallManager.delete(id).map { status =>
onComplete.apply(status)
}
}
}
示例2: AppCircuit
//设置package包名称以及导入依赖的类
package scalafiddle.client
import diode.ActionResult.{ModelUpdate, ModelUpdateSilent}
import diode._
import diode.data.{Empty, Ready}
import diode.react.ReactConnector
import upickle.default._
import scala.scalajs.js
import scala.scalajs.js.JSON
import scalafiddle.client.AppRouter.Home
import scalafiddle.shared._
object AppCircuit extends Circuit[AppModel] with ReactConnector[AppModel] {
// load from global config
def fiddleData = read[FiddleData](JSON.stringify(js.Dynamic.global.ScalaFiddleData))
override protected def initialModel =
AppModel(Home,
None,
fiddleData,
ScalaFiddleHelp(ScalaFiddleConfig.helpURL),
LoginData(Empty, Empty))
override protected def actionHandler = composeHandlers(
new FiddleHandler(zoomRW(_.fiddleData)((m, v) => m.copy(fiddleData = v)),
zoomRW(_.fiddleId)((m, v) => m.copy(fiddleId = v))),
new CompilerHandler(zoomRW(_.outputData)((m, v) => m.copy(outputData = v))),
new LoginHandler(zoomRW(_.loginData)((m, v) => m.copy(loginData = v))),
navigationHandler
)
override def handleFatal(action: Any, e: Throwable): Unit = {
println(s"Error handling action: $action")
println(e.toString)
}
override def handleError(e: String): Unit = {
println(s"Error in circuit: $e")
}
val navigationHandler: (AppModel, Any) => Option[ActionResult[AppModel]] = (model, action) =>
action match {
case NavigateTo(page) =>
Some(ModelUpdate(model.copy(navLocation = page)))
case NavigateSilentTo(page) =>
Some(ModelUpdateSilent(model.copy(navLocation = page)))
case _ =>
None
}
}
示例3: Login
//设置package包名称以及导入依赖的类
package pages
import API._
import API.Models._
import org.scalajs.dom
import org.scalajs.dom._
import scala.concurrent._
import ExecutionContext.Implicits.global
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation.JSExportTopLevel
import scala.util._
class Login {}
object Login {
@JSExportTopLevel("login")
def login(): Unit = {
val credentials = new Credentials(
document.getElementById("login-email").asInstanceOf[html.Input].value,
document.getElementById("login-password").asInstanceOf[html.Input].value
)
API.login(credentials).onComplete {
case Success(req) =>
val token = req.getResponseHeader("Authorization")
headers += ("Authorization" -> token)
document.cookie = "Authorization=" + token
document.location.pathname = "/"
case Failure(e: dom.ext.AjaxException) =>
Utils.addAlert("danger", JSON.parse(e.xhr.responseText).selectDynamic("message").asInstanceOf[String])
}
}
@JSExportTopLevel("register")
def register(): Unit = {
val user = new User(
document.getElementById("register-email").asInstanceOf[html.Input].value,
document.getElementById("register-fullname").asInstanceOf[html.Input].value,
document.getElementById("register-password").asInstanceOf[html.Input].value,
document.getElementById("register-currency").asInstanceOf[html.Input].value
)
API.register(user).onComplete {
case Success(resp) =>
val token = resp.getResponseHeader("Authorization")
headers += ("Authorization" -> token)
document.cookie = "Authorization=" + token
document.location.pathname = "/"
case Failure(e: dom.ext.AjaxException) =>
Utils.addAlert("danger", JSON.parse(e.xhr.responseText).selectDynamic("message").asInstanceOf[String])
}
}
}
示例4: ParseResultSpec
//设置package包名称以及导入依赖的类
package com.criteo.vizatra.vizsql.js.common
import org.scalatest.{FunSpec, Matchers}
import com.criteo.vizatra.vizsql
import com.criteo.vizatra.vizsql.INTEGER
import scala.scalajs.js.JSON
class ParseResultSpec extends FunSpec with Matchers {
describe("Column") {
describe("from()") {
it("converts scala Column to JS object") {
val col = Column.from(vizsql.Column("col1", INTEGER(true)))
JSON.stringify(col) shouldEqual """{"name":"col1","type":"integer","nullable":true}"""
}
}
}
describe("Table") {
describe("from()") {
it("converts scala Table to JS object") {
val table = Table.from(vizsql.Table("table1", List(vizsql.Column("col1", INTEGER(true)))), Some("schema1"))
JSON.stringify(table) shouldEqual """{"name":"table1","columns":[{"name":"col1","type":"integer","nullable":true}],"schema":"schema1"}"""
}
}
}
}
示例5: SocketJS
//设置package包名称以及导入依赖的类
package com.malliina.logstreams.js
import org.scalajs.dom
import org.scalajs.dom.CloseEvent
import org.scalajs.dom.raw.{ErrorEvent, Event, MessageEvent}
import org.scalajs.jquery.jQuery
import upickle.Invalid
import scala.scalajs.js
import scala.scalajs.js.JSON
abstract class SocketJS(wsPath: String) {
val statusElem = elem("status")
val socket: dom.WebSocket = openSocket(wsPath)
def handlePayload(payload: String)
def openSocket(pathAndQuery: String) = {
val wsUrl = s"$wsBaseUrl$pathAndQuery"
val socket = new dom.WebSocket(wsUrl)
socket.onopen = (_: Event) => setFeedback("Connected.")
socket.onmessage = (event: MessageEvent) => onMessage(event)
socket.onclose = (_: CloseEvent) => setFeedback("Connection closed.")
socket.onerror = (_: ErrorEvent) => setFeedback("Connection error.")
socket
}
def wsBaseUrl = {
val location = dom.window.location
val wsProto = if (location.protocol == "http:") "ws" else "wss"
s"$wsProto://${location.host}"
}
def onMessage(msg: MessageEvent): Unit = {
val event = JSON.parse(msg.data.toString)
if (event.event.toString == "ping") {
} else {
handlePayload(JSON.stringify(event))
}
}
def onInvalidData(message: String): PartialFunction[Invalid, Unit] = {
case Invalid.Data(jsValue, errorMessage) =>
println(s"JSON failed to parse: '$errorMessage' in value '$jsValue', message '$message'.")
case Invalid.Json(errorMessage, in) =>
println(s"Not JSON, '$errorMessage' in value '$in', message '$message'.")
}
def setFeedback(feedback: String) = statusElem html feedback
def elem(id: String) = jQuery(s"#$id")
def global = js.Dynamic.global
def validate[T: PimpJSON.Reader](in: String): Either[Invalid, T] =
PimpJSON.validate(in)
}
示例6: SearchService
//设置package包名称以及导入依赖的类
package com.searchmvc
import com.greencatsoft.angularjs
import com.greencatsoft.angularjs.core.{HttpService, Timeout}
import com.greencatsoft.angularjs.{AngularExecutionContextProvider, Service, injectable}
import prickle.Unpickle
import todomvc.example.HttpClientSupport
import scala.concurrent.Future
import scala.scalajs.js.JSON
@injectable("searchService")
class SearchService(val http: HttpService, val timeout: Timeout)
extends HttpClientSupport with AngularExecutionContextProvider with Service
{
require(http != null, "Missing argument 'http'.")
require(timeout != null, "Missing argument 'timeout'.")
def searchDmd(dmd: String, query: String): Future[Seq[SearchResult]] = flatten {
// Append a timestamp to prevent some old browsers from caching the result.
httpGet("/search/" + dmd + "/" + query)
.map(JSON.stringify(_))
.map(Unpickle[Seq[SearchResult]].fromString(_))
}
}
object SearchService
{
@injectable("searchService")
class Factory(http: HttpService, timeout: Timeout) extends angularjs.Factory[SearchService]
{
def apply(): SearchService = new SearchService(http, timeout)
}
}
示例7:
//设置package包名称以及导入依赖的类
package client.handler
import java.util.UUID
import diode.{ActionHandler, ActionResult, ModelRW}
import client.rootmodel.IntroRootModel
import client.logger
import client.services.{CoreApiOld, LGCircuit}
import shared.dtos._
import concurrent._
import ExecutionContext.Implicits._
import diode.AnyAction._
import scala.scalajs.js.JSON
import scala.util.{Failure, Success}
LGCircuit.dispatch(ShowServerError(response.getMessage))
}
val newList = value.introResponse.filterNot(
_.introSessionId.equals(introConfirmReq.introSessionId)
)
updated(IntroRootModel(newList))
case AcceptConnectNotification(connectNotification: ConnectNotification) =>
updated(IntroRootModel(Nil))
case AcceptIntroductionConfirmationResponse(introductionConfirmationResponse: IntroductionConfirmationResponse) =>
// if (introductionConfirmationResponse.sessionURI.length != 0) {
// updated(IntroRootModel(Nil))
// } else
noChange
case AddNotification(introconfirmSeq: Seq[Introduction]) =>
val modelMod =if (value.introResponse.nonEmpty) {
value.introResponse ++ introconfirmSeq.filterNot(e=>
value.introResponse.exists(p=>JSON.parse(p.introProfile).name.asInstanceOf[String] == JSON.parse(e.introProfile).name.asInstanceOf[String]))
} else {
introconfirmSeq
}
updated(IntroRootModel(modelMod))
}
}
示例8: SpotifyAPI
//设置package包名称以及导入依赖的类
package co.enear.spotifywebapp
import org.scalajs.dom.ext.Ajax
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.scalajs.js.{JSON, URIUtils}
object SpotifyAPI {
def fetchArtist(name: String): Future[Option[Artist]] = {
Ajax.get(artistSearchURL(name)) map { xhr =>
val searchResults = JSON.parse(xhr.responseText).asInstanceOf[SearchResults]
searchResults.artists.items.headOption
}
}
def fetchAlbums(artistId: String): Future[Seq[Album]] = {
Ajax.get(albumsURL(artistId)) map { xhr =>
val albumListing = JSON.parse(xhr.responseText).asInstanceOf[ItemListing[Album]]
albumListing.items
}
}
def fetchTracks(albumId: String): Future[Seq[Track]] = {
Ajax.get(tracksURL(albumId)) map { xhr =>
val trackListing = JSON.parse(xhr.responseText).asInstanceOf[ItemListing[Track]]
trackListing.items
}
}
def artistSearchURL(name: String) = s"https://api.spotify.com/v1/search?type=artist&q=${URIUtils.encodeURIComponent(name)}"
def albumsURL(artistId: String) = s"https://api.spotify.com/v1/artists/$artistId/albums?limit=50&market=PT&album_type=album"
def tracksURL(albumId: String) = s"https://api.spotify.com/v1/albums/$albumId/tracks?limit=50"
}
示例9: ScalaJSExample
//设置package包名称以及导入依赖的类
package example
import com.thoughtworks.binding.Binding.Var
import com.thoughtworks.binding.dom
import org.scalajs.dom.document
import org.scalajs.dom.ext.Ajax
import org.scalajs.dom.raw.Event
import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue
import scala.scalajs.js
import scala.scalajs.js.JSON
object ScalaJSExample extends js.JSApp {
def countRequest(data: Var[String]) = {
val url = "http://localhost:9000/count"
Ajax.get(url).onSuccess { case xhr =>
data := JSON.parse(xhr.responseText).count.toString
}
}
@dom
def render = {
val data = Var("")
countRequest(data) // initial population
<div>
<button onclick={event: Event => countRequest(data) }>
Boop
</button>
From Play: The server has been booped { data.bind } times. Shared Message: {shared.SharedMessages.itWorks}.
</div>
}
def main(): Unit = {
dom.render(document.body, render)
}
}
示例10: withStringParser
//设置package包名称以及导入依赖的类
package com.hypertino.binders.json
import java.io.{Reader, Writer}
import com.hypertino.binders.core.{BindOptions, Deserializer, Serializer}
import com.hypertino.binders.json.api.{JsonBindersFactoryApi, JsonGeneratorApi, JsonParserApi}
import com.hypertino.inflector.naming.{Converter, PlainConverter}
import scala.scalajs.js
import scala.scalajs.js.JSON
trait JsonBindersFactory[C <: Converter, S <: Serializer[C], D <: Deserializer[C]]
extends JsonBindersFactoryApi[C, S, D] {
override def withStringParser[T](jsonString: String)
(codeBlock: D ? T)
(implicit bindOptions: BindOptions): T = {
val adapter = new JsParserAdapter(JSON.parse(jsonString))
val jds = createDeserializer(adapter)
codeBlock(jds)
}
override def withReader[T](reader: Reader)
(codeBlock: (D) ? T)
(implicit bindOptions: BindOptions): T = {
val stringBuilder = new StringBuilder
val len = 256
val buffer = new Array[Char](len)
var readed = len
while (readed == len) {
readed = reader.read(buffer, 0, len)
stringBuilder.append(buffer, 0, readed)
}
withStringParser(stringBuilder.toString())(codeBlock)
}
def withJsonObjectParser[T](jsonObject: js.Dynamic)
(codeBlock: D ? T)
(implicit bindOptions: BindOptions): T = {
withJsonParserApi(new JsParserAdapter(jsonObject))(codeBlock)
}
override def withWriter(writer: Writer)
(codeBlock: S ? Unit)
(implicit bindOptions: BindOptions): Unit = {
withJsonGeneratorApi(new JsGeneratorAdapter(writer))(codeBlock)
}
}
object JsonBindersFactory {
implicit val defaultJsonBindersFactory = new DefaultJsonBindersFactory[PlainConverter.type]
def findFactory[C <: Converter, S <: Serializer[C], D <: Deserializer[C]]()
(implicit factory: JsonBindersFactory[C, S, D]): JsonBindersFactory[C, S, D] = factory
}