本文整理汇总了Scala中org.json.JSONObject类的典型用法代码示例。如果您正苦于以下问题:Scala JSONObject类的具体用法?Scala JSONObject怎么用?Scala JSONObject使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了JSONObject类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: MixpanelUtil
//设置package包名称以及导入依赖的类
package com.nulabinc.backlog.migration.common.utils
import java.util.Date
import com.mixpanel.mixpanelapi.{ClientDelivery, MessageBuilder, MixpanelAPI}
import org.json.JSONObject
object MixpanelUtil {
def track(token: String, data: TrackingData) = {
val props = new JSONObject()
props.put("Source URL", data.srcUrl)
props.put("Destination URL", data.dstUrl)
props.put("Source Project Key", data.srcProjectKey)
props.put("Destination Project Key", data.dstProjectKey)
props.put("Source Space Created Date", data.srcSpaceCreated)
props.put("Destination Space Created Date", data.dstSpaceCreated)
props.put("Between Created Date And Migrated Date", diff(data.dstSpaceCreated))
props.put("Product", data.product)
val messageBuilder = new MessageBuilder(token)
val distinctId = s"${data.envname}-${data.spaceId}-${data.userId}"
val event = messageBuilder.event(distinctId, "Project Migrated", props)
val delivery = new ClientDelivery()
delivery.addMessage(event)
val mixpanel = new MixpanelAPI()
mixpanel.deliver(delivery)
}
private[this] def diff(dstSpaceCreated: String): Long = {
val dstSpaceCreatedTime = DateUtil.tryIsoParse(Some(dstSpaceCreated)).getTime()
val nowTime = (new Date()).getTime()
(nowTime - dstSpaceCreatedTime) / (1000 * 60 * 60 * 24)
}
}
case class TrackingData(product: String,
envname: String,
spaceId: Long,
userId: Long,
srcUrl: String,
dstUrl: String,
srcProjectKey: String,
dstProjectKey: String,
srcSpaceCreated: String,
dstSpaceCreated: String)
示例2: JSONUtil
//设置package包名称以及导入依赖的类
package amit.common.json
import amit.common.Util
import org.json.JSONArray
import org.json.JSONObject
import org.json.JSONTokener
import scala.collection.JavaConversions._
object JSONUtil {
def decodeJSONArray(jsonString:String) = {
val ja = new JSONArray(jsonString)
new Array[Int](ja.length).indices.map(i => ja.get(i)).toArray
}
def getJSONKeys(jsonString:String) = {
val jo = new JSONTokener(jsonString).nextValue().asInstanceOf[JSONObject];
jo.keys.map(_.toString).toList
}
def getJSONParams(names:List[String], jsonString:String) = {
val jo = new JSONTokener(jsonString).nextValue().asInstanceOf[JSONObject];
names.indices.map(i => jo.getString(names.apply(i)))
}
def encodeJSONSeq(s:Seq[_]) = encodeJSONArray(s.toArray)
def encodeJSONArray(a:Array[_]) = new JSONArray(a)
def createJSONString(keys:Array[String], vals:Array[_]) = createJSONObject(keys, vals).toString
def createJSONObject(keys:Array[String], vals:Array[_]) = {
val jo = new JSONObject
keys.indices.foreach(i => jo.put(keys.apply(i), vals.apply(i)))
jo
}
def jsonStringToXML(s:String) = try scala.xml.XML.loadString("<JSON>"+org.json.XML.toString(new JSONObject(s))+"</JSON>") catch {
case e:Any =>
if (Util.debug) e.printStackTrace
<error>{e.getMessage}</error>
}
trait JsonFormatted {
val keys:Array[String]
val vals:Array[Any]
override def toString = createJSONString(keys, vals)
}
}
示例3: SocialNetworkProvider
//设置package包名称以及导入依赖的类
package ru.izebit.service
import java.util.concurrent.TimeUnit
import org.apache.http.client.fluent.Request
import org.json.JSONObject
import org.springframework.stereotype.Component
import ru.izebit.model.Sex
import scala.collection.JavaConversions.asScalaIterator
@Component
class SocialNetworkProvider {
private val API_VERSION = "5.62"
private val TIMEOUT = TimeUnit.SECONDS.toMillis(5).asInstanceOf[Int]
private val HOST = "https://api.vk.com/method/"
def search(city: Int, sex: Sex, count: Int, offset: Int, token: String): List[String] = {
val isEnableExternalSearch = java.lang.Boolean.getBoolean("external-search-enable")
if (!isEnableExternalSearch)
return List.empty
val sortType = 1
val isHasPhoto = 1
val online = 1
val status = 6
val param = s"users.search?" +
s"city=$city&sex=$sex&count=$count&offset=$offset" +
s"&sort=$sortType&status=$status&online=$online&has_photo=$isHasPhoto" +
s"&access_token=$token&v=$API_VERSION"
//todo ??????? ????????? ???????? ??????? ? ?????? ?????
val content =
Request
.Get(HOST + param)
.connectTimeout(TIMEOUT)
.execute().returnContent().asString()
val jsonResponse = new JSONObject(content)
jsonResponse
.getJSONArray("items")
.iterator()
.map(e => e.asInstanceOf[JSONObject])
.map(e => e.getString("id"))
.toList
}
}
示例4: Streaming
//设置package包名称以及导入依赖的类
package Pipeline
import java.util.{Calendar, Properties}
import collection.JavaConverters._
import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkConf
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.KafkaUtils
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.json.JSONObject
import com.typesafe.scalalogging.slf4j.LazyLogging
import org.apache.log4j.BasicConfigurator
class Streaming(var server: String, var receiveTopic: String, var sendTopic: String) extends LazyLogging{
// Kafka Parameters
val props = new Properties()
props.put("bootstrap.servers", server)
props.put("client.id", "Streaming")
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer")
val producer = new KafkaProducer[String, String](props)
BasicConfigurator.configure()
// Kafka stream
val conf = new SparkConf().setAppName("DataPipeline").setMaster("local[2]")
val ssc = new StreamingContext(conf, Seconds(2))
val kafkaParams = Map[String, Object](
"bootstrap.servers" -> server,
"key.deserializer" -> classOf[StringDeserializer],
"value.deserializer" -> classOf[StringDeserializer],
"auto.offset.reset" -> "latest",
"group.id" -> "use_a_separate_group_id_for_each_stream"
)
val stream = KafkaUtils createDirectStream[String, String](
ssc,
PreferConsistent,
Subscribe[String, String](Array(receiveTopic), kafkaParams)
)
stream.foreachRDD(rdd => {
val newRdd = rdd.map(record => {
val tmp = new JSONObject(record.value())
(tmp.get("StockSymbol"), (tmp.get("LastTradePrice").toString.toFloat, 1))
}).reduceByKey((x, y) => (x._1 + y._1, x._2 + y._2)).map(x => (x._1, x._2._1 / x._2._2))
val result = newRdd.collect()
for (ele <- result) {
val msg = new JSONObject(Map("StockSymbol" -> ele._1, "LastTradePrice" -> ele._2,
"SendTime" -> System.currentTimeMillis.toDouble / 1000).asJava)
val data = new ProducerRecord[String, String](sendTopic, msg.toString)
producer.send(data)
logger.info("Successfully send the averaged price " + msg)
}
})
}
示例5: Producer
//设置package包名称以及导入依赖的类
package Pipeline
import java.io.IOException
import java.util.Properties
import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}
import GoogleFinanceJavaApi.GoogleFinance
import org.json.{JSONException, JSONObject}
import com.typesafe.scalalogging.slf4j.LazyLogging
import org.apache.log4j.BasicConfigurator
class Producer(var server: String, var sendTopic: String) extends LazyLogging {
val props = new Properties()
props.put("bootstrap.servers", server)
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer")
val producer = new KafkaProducer[String, String](props)
BasicConfigurator.configure()
logger.info("producer has been built")
def send(code: String) = {
def getQuotes(code: String) = GoogleFinance.getQuotes(code)
val msg = new JSONObject(getQuotes(code))
val data = new ProducerRecord[String, String](sendTopic, msg.toString)
producer.send(data)
logger.info("Successfully send the msg " + msg)
}
}
示例6: Hastebin
//设置package包名称以及导入依赖的类
package se4jda
import java.io.{BufferedReader, InputStreamReader}
import okhttp3.RequestBody
import org.json.{JSONObject, JSONTokener}
object Hastebin {
def apply(content: String) =
Post("https://hastebin.com/documents", RequestBody.create(null, content))
.header("Content-Type", "text/plain")
.call
.use(r => new BufferedReader(new InputStreamReader(r.body.byteStream)).use { re =>
val json = new JSONObject(new JSONTokener(re))
s"https://hastebin.com/${json.getString("key")}"
})
}
示例7: Dependency
//设置package包名称以及导入依赖的类
package config.wiz
import org.json.JSONObject
case class Dependency(val name : String, val version : Int) {
var fileFetcher : FileFetcher = null
def url : String = s"${name}@${version}"
}
object Dependency {
def fromJSON(json: JSONObject): Dependency = {
val name = json getString "name"
val version = json getInt "version"
Dependency(name, version)
}
}
示例8: extractors
//设置package包名称以及导入依赖的类
package me.hawkweisman.jsonQuery
import me.hawkweisman.jsonQuery.queries._
import org.json.{JSONArray, JSONObject}
import scala.language.postfixOps
import scala.reflect.ClassTag
object extractors {
sealed abstract class Json[T: FromJson#Element : ClassTag] {
@inline def unapply(query: Queryable): Option[T]
= query.asOption[T]
}
object JsonInt extends Json[Int]
object JsonDouble extends Json[Double]
object JsonBool extends Json[Boolean]
object JsonString extends Json[String]
object JsonArray extends Json[JSONArray] {
@inline def unapplySeq(query: Queryable): Option[IndexedSeq[Index]]
= query.asOption[JSONArray] map { IndexableJsonArray }
}
object JsonObject extends Json[JSONObject] {
@inline def unapplySeq(query: Queryable): Option[Seq[(String, Query)]]
= query.asOption[JSONObject] map { _ toSeq }
}
}
示例9: BignumSpec
//设置package包名称以及导入依赖的类
package me.hawkweisman
import java.math.BigInteger
import BigInt.javaBigInteger2bigInt
import org.json.JSONObject
import org.scalatest.{Matchers, OptionValues, TryValues, WordSpec}
import jsonQuery.queries._
import scala.util.Success
class BignumSpec
extends WordSpec
with Matchers
with TryValues
with OptionValues {
val aBigInt = BigInt(Int.MaxValue) + 1
val aBigDecimal = BigDecimal(Double.MaxValue) + 1
// NOTE: that these are all ignored becasue org.json's handling of bignums is
// Highly Nonsensical, and I am not currently sure how to handle it.
// - eliza, 7/23/16
"A simple JSON object" when {
"querying for a key that exists" should {
"extract a big integer as a BigInt" ignore {
val json = new JSONObject(s"""{"element":$aBigInt}""")
(json \ "element").as[BigInteger] shouldEqual Success(aBigInt)
}
"not extract a big integer as a BigDecimal" ignore {
val json = new JSONObject(s"""{"element":$aBigInt}""")
(json \ "element").as[BigDecimal] should be a 'failure
}
"extract a big decimalt number as a BigDecimal" ignore {
val json = new JSONObject(s"""{"element":$aBigDecimal}""")
(json \ "element").as[BigDecimal] shouldEqual Success(aBigDecimal)
}
"not extract a big decimal number as a BigInt" ignore {
val json = new JSONObject(s"""{"element":$aBigDecimal}""")
(json \ "element").as[BigInteger] should be a 'failure
}
}
}
}
示例10: Song
//设置package包名称以及导入依赖的类
package net.thereturningvoid.bladebot.song
import org.json.JSONObject
import scala.util.Random
abstract class Song(val name: String, val artist: String, val id: String) {
def get: JSONObject
}
case class SoundcloudSong(override val name: String, override val artist: String, override val id: String) extends Song(name, artist, id) {
val songObject: JSONObject = new JSONObject().put("songName", name).put("artist", artist).put("id", id)
def this(json: JSONObject) = this(
if (json.has("error")) json.getString("error") else json.getString("title"),
if (json.has("error")) "error" else json.getJSONObject("user").getString("username"),
if (json.has("error")) "0" else Math.abs(Random.nextInt).toString)
def get: JSONObject = songObject
override def toString: String = songObject.toString(2)
}
object SoundcloudSong {
def fromSongJSON(json: JSONObject): SoundcloudSong = {
new SoundcloudSong(json.getString("songName"), json.getString("artist"), json.getString("id"))
}
}