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


Scala JSON类代码示例

本文整理汇总了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)
    }
  }
} 
开发者ID:kindone,项目名称:iw2,代码行数:61,代码来源:IndexApp.scala

示例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
  }
} 
开发者ID:scalafiddle,项目名称:scalafiddle-editor,代码行数:52,代码来源:AppCircuit.scala

示例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])
    }
  }
} 
开发者ID:MathieuUrstein,项目名称:HEIG.SCALA.Projet,代码行数:52,代码来源:Login.scala

示例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"}"""
      }
    }
  }
} 
开发者ID:criteo,项目名称:vizsql,代码行数:27,代码来源:ParseResultSpec.scala

示例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)
} 
开发者ID:malliina,项目名称:logstreams,代码行数:59,代码来源:SocketJS.scala

示例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)
  }

} 
开发者ID:pharmpress,项目名称:DmdBrowserScalaJs,代码行数:40,代码来源:SearchService.scala

示例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))
  }

} 
开发者ID:francescopersico,项目名称:i,代码行数:46,代码来源:IntroductionHandler.scala

示例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"
} 
开发者ID:enear,项目名称:scalajs-react-guide-part1,代码行数:36,代码来源:SpotifyAPI.scala

示例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)
  }
} 
开发者ID:Algomancer,项目名称:Full-Stack-Scala-Starter,代码行数:42,代码来源:ScalaJSExample.scala

示例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
} 
开发者ID:hypertino,项目名称:json-binders,代码行数:55,代码来源:JsonBindersFactory.scala


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