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


Scala JSON类代码示例

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


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

示例1: addOrganizationMembership

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

import http.Response

import scala.util.{Failure, Success}
import scala.util.parsing.json.JSON


  def addOrganizationMembership(org:String, userName:String, role:String):Either[String, Option[Any]] = {
    putData(
      s"/orgs/$org/memberships/$userName",
      generateHeaders.::(new http.Header("Content-Type", "application/json")),
      Map(
        "role" -> role // member, maintener
      )
    ) match {
      case Success(resp:Response) =>
        if (http.isOk(resp.code)) Right(JSON.parseFull(resp.data)) else Left(resp.message)
      case Failure(err) =>  Left(err.getMessage)
    }
  }
} 
开发者ID:bots-squad,项目名称:tentacle-scala,代码行数:23,代码来源:Organizations.scala

示例2: TypoFixer

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

import java.io.File
import scala.io.Source
import scala.util.parsing.json.JSON

import fgc.model.Transform

class TypoFixer() {
    private val CHARACTER_FILE_PATH = "reference/character_typo.json"
    private val PLAYER_FILE_PATH = "reference/player_typo.json"

    private def loadFile(filePath: String): Map[String, List[String]] = {
        if (!(new File(filePath).exists)){
            throw new Exception
        }
        val jsonString = Source.fromFile(filePath).getLines.mkString
        val jsonMap: Map[String, Any] = JSON.parseFull(jsonString).get.asInstanceOf[Map[String, Any]]
        jsonMap.map { case(fix, typos) =>
            (fix, typos.asInstanceOf[List[String]])
        }.toMap
    }

    private def genInverse(nameMap: Map[String, List[String]]): Map[String, String] = {
        nameMap.map { case(fix, typos) =>
            typos.map(typo => (Transform.toKey(typo), Transform.toKey(fix)))
        }.flatten.toMap
    }

    private val charNameMap: Map[String, List[String]] = loadFile(CHARACTER_FILE_PATH)
    private val charInverse = genInverse(charNameMap)

    private val playerNameMap: Map[String, List[String]] = loadFile(PLAYER_FILE_PATH)
    private val playerInverse = genInverse(playerNameMap)

    def fixPlayer(rawName: String): String = {
        val key = Transform.toKey(rawName)
        playerInverse.getOrElse(key, key)
    }

    def fixCharacter(rawName: String): String = {
        val key = Transform.toKey(rawName)
        charInverse.getOrElse(key, key)
    }
} 
开发者ID:mpaulweeks,项目名称:fgc-video,代码行数:46,代码来源:typo.scala

示例3: PerfEventEncoder

//设置package包名称以及导入依赖的类
package akka.persistence.pg.perf

import akka.persistence.pg.JsonString
import akka.persistence.pg.event.JsonEncoder
import akka.persistence.pg.perf.Messages.Altered

import scala.util.parsing.json.JSON

class PerfEventEncoder extends JsonEncoder {

  override def toJson = {
    case Altered(text, created) => JsonString(s"""{
                                                  | "type": "altered",
                                                  | "txt": "$text",
                                                  | "created": "$created"
                                                  |}""".stripMargin)
  }

  private def parseJsonString(jsonString: JsonString) = {
    JSON.parseFull(jsonString.value).get.asInstanceOf[Map[String, Any]]
  }

  private def altered(jsValue: Map[String, Any]): Altered = {
    Altered(jsValue("txt").asInstanceOf[String], jsValue("created").asInstanceOf[Long])
  }


  override def fromJson = {
    case(json, _) => altered(parseJsonString(json))
  }

} 
开发者ID:WegenenVerkeer,项目名称:akka-persistence-postgresql,代码行数:33,代码来源:PerfEventEncoder.scala

示例4: MarathonDiscoveryService

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

import org.slf4j.LoggerFactory

import scala.io.Source._
import scala.util.Random
import scala.util.parsing.json.JSON

class MarathonDiscoveryService(dnsIp: String, dnsPort: Int) extends DiscoveryService {
  val logger = LoggerFactory.getLogger(MarathonDiscoveryService.this.getClass)

  def getIpAndPort(serviceId: String) : (String, Int) = {
    val mesosUrl = s"http://${this.dnsIp}:${this.dnsPort}/v1/services/_${serviceId}._tcp.marathon.mesos"
    //val response = utilities.MarathonServiceDiscovery.getURL(mesosUrl)
    logger.debug(s"Mesos Url: ${mesosUrl}")
    val response = MarathonDiscoveryService.getURL(mesosUrl)
    val mapList = JSON.parseFull(response).asInstanceOf[Some[List[Map[String, Any]]]]
    val addressesList = mapList.getOrElse(List(Map()).asInstanceOf[List[Map[String, Any]]])
    val length = addressesList.length
    if(length>0) {
      val random = Random
      val randomIndex = random.nextInt(length)
      logger.debug(s"Addresses length: ${length}, random: ${random}")
      logger.debug(s"AddressesList: ${addressesList}")
      val firstAddress = addressesList(randomIndex)
      logger.debug(s"Selected address: ${firstAddress}")
      val ip = firstAddress("ip").toString
      val port = firstAddress("port").toString.toInt
      (ip, port)
    }else{
      throw new Exception(s"Marathon Service ${mesosUrl} not found")
    }
  }
}

object MarathonDiscoveryService {

  def getURL(url:String): String = {
    try {
      fromURL(url)("UTF-8").mkString
    }catch {
      case e: Exception => {
        fromURL(url)("ISO-8859-1").mkString
      }
    }
  }


} 
开发者ID:MixedEmotions,项目名称:Orchestrator,代码行数:50,代码来源:MarathonDiscoveryService.scala

示例5: Main

//设置package包名称以及导入依赖的类
package com.remark.lunarrover

import java.util

import com.sun.deploy.util.StringUtils

import scala.collection.immutable.Range.Double
import scala.io.Source
import scala.util.parsing.json.JSON

/**
  * Created by xinruyi on 2017/3/15.
  */
object Main {
  def main(args: Array[String]): Unit = {
    /**
      * 1.start ControlCenter
      */
      ControlCenter.start()

    /**
      * 2.start Lunar Rovers
      */

    val text:String = Source.fromFile("lunarrover/linesInfo.txt").mkString
    val jsonTxt = JSON.parseFull(text)
    jsonTxt match {
      case Some(map1:Map[String,Any])=> {
        map1.values.map(ta=> Option(ta) match {
          case Some(map2:Map[String,Any])=>{
            val idx = map2("idx").toString
            val startPosition = map2("start").toString
            val endPosition = map2("end").toString
            val (startX,startY) = Utils.listStrPosition2Tuple(startPosition)
            val (endX,endY) = Utils.listStrPosition2Tuple(endPosition)
            val speed = map2("speed").toString.toDouble
            (new LunarRover(idx,new Position(startX,startY),new Position(startX,startY),new Position(endX,endY), speed)).start()
          }
          case None=>println("parse failed inner")
        })
      }
      case None =>println("parse failed outer")
    }


  }
} 
开发者ID:KinusHsin,项目名称:Remark,代码行数:48,代码来源:Main.scala

示例6: CommandStreamProcessor

//设置package包名称以及导入依赖的类
package com.crystal
package processors

// Spark
import org.apache.spark.streaming.kinesis._
import org.apache.spark.streaming.{ Duration, StreamingContext }
import org.apache.spark.streaming.dstream.DStream
import org.apache.spark.storage.StorageLevel
import com.amazonaws.services.kinesis.clientlibrary.lib.worker.InitialPositionInStream

// JSON Parsing
import scala.util.parsing.json.JSON

object CommandStreamProcessor {
  def setup(appConfig: AppConfig, streamingCtx: StreamingContext) = {
    val cmdStream = getCommandStream(appConfig, streamingCtx)

    cmdStream.foreachRDD { rdd =>
      rdd.foreach{ cmd =>
        println("--- Command Received ---")
      }
    }
  }

  private def getCommandStream(
    appConfig: AppConfig,
    streamingCtx: StreamingContext): DStream[Map[String, Any]] = {
    val stream = KinesisUtils.createStream(
      streamingCtx,
      appConfig.commandAppName,
      appConfig.commandStreamName,
      s"kinesis.${appConfig.regionName}.amazonaws.com",
      appConfig.regionName,
      InitialPositionInStream.LATEST,
      Duration(appConfig.checkpointInterval),
      StorageLevel.MEMORY_AND_DISK_2
    )

    stream
      .map { byteArray => new String(byteArray) }
      .map { jsonStr => JSON.parseFull(jsonStr).get.asInstanceOf[Map[String, Any]] }
  }

} 
开发者ID:crystal-project-inc,项目名称:streaming_user_segmentation,代码行数:45,代码来源:CommandStreamProcessor.scala

示例7: JsonService

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

import io.cronit.common.SchedulerServiceException
import io.cronit.utils.Configuration

import scala.util.parsing.json.JSON

trait JsonServiceComponent {
  this: Configuration =>
  val jsonService: JsonService

  class JsonService {

    def deserializeAsMap(content: String): Map[String, Any] = {
      try {
        JSON.parseFull(content).get.asInstanceOf[Map[String, Any]]
      } catch {
        case t: Throwable => throw new SchedulerServiceException(s"Deserialize error ${content} cannot deserialize to Json", t)
      }
    }
  }

} 
开发者ID:212data,项目名称:cronit-service,代码行数:24,代码来源:JsonServiceComponent.scala

示例8: SampleJob

//设置package包名称以及导入依赖的类
import org.apache.spark.SparkContext
import org.apache.spark.SparkConf

import scala.util.parsing.json.JSON
import utilities.Utility._

object SampleJob {

  var request_id: String = null
  var value: Any = null
  var value2: Any = null

  def main(args: Array[String]) {
    try {
      val arguments = args.toList
      request_id = arguments(0)
      set_parameters(arguments(1))
      val conf = new SparkConf().setAppName("SampleJob")
      val sc = new SparkContext(conf)
      val response = run_job(sc)
      store_status("completed", request_id)
      store_result(response, request_id)
    }
    catch {
      case exception: Exception => {
        println(exception)
        val exception_string = create_error_response(exception.toString)
        store_status("error", request_id)
        store_result(exception_string, request_id)
      }
    }
  }

  def run_job(sc: SparkContext): String = {
    val rdd_count = sc.parallelize("r_count").count()
    val response = create_ok_response(rdd_count)
    response
  }

  def create_ok_response(rdd_count: Long): String = {
    """ {"rdd_count": """ + rdd_count + "}"
  }

  def set_parameters(argument_string: String) = {
    val argument_json = JSON.parseFull(argument_string).get
    value = argument_json.asInstanceOf[Map[String, Any]]("string")
    value2 = argument_json.asInstanceOf[Map[String, Any]]("array")
  }
} 
开发者ID:ahamshubham,项目名称:simple-spark-jobserver,代码行数:50,代码来源:SampleJob.scala

示例9: useJsonHelper

//设置package包名称以及导入依赖的类
import com.argcv.valhalla.string.json.JsonHelper._
import com.argcv.valhalla.utils.Awakable
import org.slf4j.Logger

import scala.collection.mutable.{Map => MMap}
import scala.util.parsing.json.JSON


  def useJsonHelper(url:String, logger: Logger): Unit = {
    case class ConfAuthorsResult(name:String)
    case class ConfPaperResult(pid:String, title:String, `abstract`:String, authors:List[ConfAuthorsResult], trackname:String, keywords:String, liked:Boolean, num_liked:Int, pub_number:Int, num_viewed:Int)
    case class PaperResult(status:Boolean, res:List[ConfPaperResult])

    val timeStart = System.currentTimeMillis()
    val dataStream: String = scala.io.Source.fromURL(url).mkString
    val timeGetData = System.currentTimeMillis()
    logger.info(s"[JsonHelper] time cost in reading .. ${timeGetData - timeStart}")
    dataStream.parseJsonToClass[PaperResult] match {
      case Some(pr) =>
        logger.info(s"parsed, status: ${pr.status}")
        if(pr.status) {
          logger.info(s"count ${pr.res.size}")
          if(pr.res.nonEmpty) {
            logger.info(pr.res.head.toJson(false))
          }
        }
      case None =>
        logger.warn("parse failed")
    }

    val timeParseData = System.currentTimeMillis()
    logger.info(s"[JsonHelper] time parse data ... ${timeParseData - timeGetData}")
    logger.info(s"[JsonHelper] finished , all time cost : ${System.currentTimeMillis() - timeStart}")
  }


  val JSON_URL = "http://api.aminer.org/api/pschedule/conference/CIKM%202016/papers"
  useJSON(JSON_URL, logger)
  useJsonHelper(JSON_URL, logger)
} 
开发者ID:yuikns,项目名称:scala-json-parser-demo,代码行数:41,代码来源:Launcher.scala

示例10: createOrganizationRepository

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

import http.Response

import scala.util.{Failure, Success}
import scala.util.parsing.json.JSON


  def createOrganizationRepository(name:String, description:String, organization:String, isPrivate:Boolean, hasIssues:Boolean):Either[String, Option[Any]] = {
    postData(
      s"/orgs/$organization/repos",
      generateHeaders.::(new http.Header("Content-Type", "application/json")),
      Map(
        "name" -> name,
        "description" -> description,
        "private" -> isPrivate,
        "has_issues" -> hasIssues,
        "has_wiki" -> true,
        "auto_init" -> true
      )
    ) match {
      case Success(resp:Response) =>
        if (http.isOk(resp.code)) Right(JSON.parseFull(resp.data)) else Left(resp.message)
      case Failure(err) =>  Left(err.getMessage)
    }
  }
} 
开发者ID:bots-squad,项目名称:tentacle-scala,代码行数:28,代码来源:Repositories.scala


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