本文整理汇总了Scala中spray.json.JsArray类的典型用法代码示例。如果您正苦于以下问题:Scala JsArray类的具体用法?Scala JsArray怎么用?Scala JsArray使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了JsArray类的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: SendTweet
//设置package包名称以及导入依赖的类
package main.scala
import scala.collection.mutable.ArrayBuffer
import spray.json.DefaultJsonProtocol
import spray.json.DeserializationException
import spray.json.JsArray
import spray.json.JsNumber
import spray.json.JsObject
import spray.json.JsString
import spray.json.JsValue
import spray.json.JsonFormat
import spray.json.pimpAny
trait JsonFormats extends DefaultJsonProtocol {
case class SendTweet(userId: Int, time: Long, msg: String)
case class UserProfile(id: Int, name: String, statusCount: Int, favoritesCount: Int, followersCount: Int, followingCount: Int)
case class SendMsg(senderId: Int, time: Long, msg: String, recepientId: Int)
implicit val tweetFormat = jsonFormat3(SendTweet)
implicit val userProfileFormat = jsonFormat6(UserProfile)
implicit val reTweetFormat = jsonFormat4(SendMsg)
implicit object TimelineJsonFormat extends JsonFormat[Project4Server.Tweets] {
def write(c: Project4Server.Tweets) = JsObject(
"authorId" -> JsNumber(c.authorId),
"message" -> JsString(c.message),
"timeStamp" -> JsString(c.timeStamp.toString),
"tweetId" -> JsString(c.tweetId),
"mentions" -> JsArray(c.mentions.map(_.toJson).toVector),
"hashTags" -> JsArray(c.hashtags.map(_.toJson).toVector))
def read(value: JsValue) = {
value.asJsObject.getFields("tweetId", "authorId", "message", "timeStamp", "mentions", "hashTags") match {
case Seq(JsString(tweetId), JsNumber(authorId), JsString(message), JsString(timeStamp), JsArray(mentions), JsArray(hashTags)) =>
new Project4Server.Tweets(tweetId, authorId.toInt, message, timeStamp.toLong, mentions.map(_.convertTo[String]).to[ArrayBuffer], hashTags.map(_.convertTo[String]).to[ArrayBuffer])
case _ => throw new DeserializationException("Tweets expected")
}
}
}
implicit object MessagesJsonFormat extends JsonFormat[Project4Server.Messages] {
def write(c: Project4Server.Messages) = JsObject(
"authorId" -> JsNumber(c.authorId),
"message" -> JsString(c.message),
"timeStamp" -> JsString(c.timeStamp.toString),
"tweetId" -> JsString(c.tweetId),
"mentions" -> JsArray(c.mentions.map(_.toJson).toVector),
"hashTags" -> JsArray(c.hashtags.map(_.toJson).toVector),
"recepientId" -> JsNumber(c.recepientId))
def read(value: JsValue) = {
value.asJsObject.getFields("tweetId", "authorId", "message", "timeStamp", "mentions", "hashTags", "recepientId") match {
case Seq(JsString(tweetId), JsNumber(authorId), JsString(message), JsString(timeStamp), JsArray(mentions), JsArray(hashTags), JsNumber(recepientId)) =>
new Project4Server.Messages(recepientId.toInt, tweetId, authorId.toInt, message, timeStamp.toLong, mentions.map(_.convertTo[String]).to[ArrayBuffer], hashTags.map(_.convertTo[String]).to[ArrayBuffer])
case _ => throw new DeserializationException("Tweets expected")
}
}
}
}
示例2:
//设置package包名称以及导入依赖的类
package com.shashank.akkahttp.project
import java.util.concurrent.ConcurrentHashMap
import akka.actor.ActorSystem
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import com.shashank.akkahttp.project.Models.{LoadRequest, ServiceJsonProtoocol}
import spray.json.JsArray
import scala.collection.JavaConverters._
import spray.json.{DefaultJsonProtocol, JsArray, pimpAny}
import spray.json.DefaultJsonProtocol._
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql._
trait RestService {
implicit val system: ActorSystem
implicit val materializer: ActorMaterializer
implicit val sparkSession: SparkSession
val datasetMap = new ConcurrentHashMap[String, Dataset[Row]]()
import ServiceJsonProtoocol._
val route =
pathSingleSlash {
get {
complete {
"welcome to rest service"
}
}
} ~
path("load") {
post {
entity(as[LoadRequest]) {
loadRequest => complete {
val id = "" + System.nanoTime()
val dataset = sparkSession.read.format("csv")
.option("header", "true")
.load(loadRequest.path)
datasetMap.put(id, dataset)
id
}
}
}
} ~
path("view" / """[\w[0-9]-_]+""".r) { id =>
get {
complete {
val dataset = datasetMap.get(id)
dataset.take(10).map(row => row.toString())
}
}
}
}
示例3: BooksFoundFormat
//设置package包名称以及导入依赖的类
package com.jjabuk.bookstore.catalog.protocols
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import com.jjabuk.bookstore.catalog.protocols.CatalogueProtocol.{Book, BookAdded, BooksFound}
import reactivemongo.bson.BSONObjectID
import spray.json.{DefaultJsonProtocol, JsArray, JsObject, JsString, JsValue, RootJsonFormat}
trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
implicit val BookAddedFormat = jsonFormat1(BookAdded.apply)
implicit object BooksFoundFormat extends RootJsonFormat[BooksFound] {
override def read(json: JsValue): BooksFound = ???
override def write(b: BooksFound): JsValue = JsObject(
"books" -> JsArray(b.books.map(book => BookFormat.write(book)).toVector)
)
}
implicit object BookFormat extends RootJsonFormat[Book] {
override def read(value: JsValue) = {
val uuid = fromField[Option[String]](value, "uuid")
val isbn = fromField[String](value, "isbn")
val title = fromField[String](value, "title")
val review = fromField[Option[String]](value, "review")
val publisher = fromField[Option[String]](value, "publisher")
Book(uuid.getOrElse(BSONObjectID.generate().stringify), isbn, title, review, publisher)
}
override def write(obj: Book): JsValue = JsObject(
"uuid" -> JsString(obj.uuid),
"isbn" -> JsString(obj.isbn),
"title" -> JsString(obj.title),
"review" -> JsString(obj.review.getOrElse("")),
"publisher" -> JsString(obj.publisher.getOrElse(""))
)
}
}
示例4: MapConcat
//设置package包名称以及导入依赖的类
package net.ruippeixotog.scalafbp.component.stream
import akka.actor.Props
import rx.lang.scala.Observable
import spray.json.{ JsArray, JsValue }
import net.ruippeixotog.scalafbp.component._
import net.ruippeixotog.scalafbp.util.NashornEngine
case object MapConcat extends Component {
val name = "stream/MapConcat"
val description = "Transforms the elements of a stream into arrays of elements and flatterns them"
val icon = Some("code")
val inPort = InPort[JsValue]("in", "The stream to transform")
val funcPort = InPort[String]("func", "The function with argument x to use for transformation. " +
"Must return an array. While not defined, all elements pass untouched.")
val inPorts = List(inPort, funcPort)
val outPort = OutPort[JsValue]("out", "The transformed stream")
val outPorts = List(outPort)
val instanceProps = Props(new ComponentActor(this) with NashornEngine {
val defaultFunc = Observable.just[JsFunction](JsArray(_))
val func = defaultFunc ++ funcPort.stream.map(JsFunction(_))
inPort.stream.withLatestFrom(func) { (x, f) => f(x) }.flatMapIterable {
case JsArray(elems) => elems
case js => throw new IllegalArgumentException(
s"The value ${js.compactPrint} returned by the function is not an array")
}.pipeTo(outPort)
})
}
示例5: JSON
//设置package包名称以及导入依赖的类
package falkner.jayson.metrics.io
import java.nio.file.{Files, Path}
import falkner.jayson.metrics._
import spray.json.{JsArray, JsBoolean, JsNumber, JsObject, JsString, JsValue}
import scala.util.{Failure, Success, Try}
object JSON {
def apply(out: Path, ml: Metrics): Path = apply(out, Seq(ml))
def apply(out: Path, mls: Seq[Metrics]): Path = Files.write(mkdir(out), JsObject(mls.map(export): _*).prettyPrint.getBytes)
def export(o: Metrics): (String, JsValue) = (o.namespace, JsObject(export(o.values): _*))
def export(o: List[Metric]): List[(String, JsValue)] = o.flatMap(_ match {
case n: Num => noneIfError[JsNumber]((n.name, JsNumber(n.value)))
case s: Str => noneIfError[JsString]((s.name, JsString(s.value)))
case b: Bool => noneIfError[JsBoolean]((b.name, JsBoolean(b.value)))
case n: NumArray => noneIfError[JsArray]((n.name, JsArray(n.values.asInstanceOf[Seq[Int]].map(m => JsNumber(m)).toVector)))
// flatten out categorical distributions and keep key order
case cd: CatDist => noneIfError[JsObject](
(cd.name, JsObject(
List(("Name", JsString(cd.name)), ("Samples", JsNumber(cd.samples))) ++
cd.bins.keys.map(k => cd.bins(k) match {
case s: Short => (k, JsNumber(s))
case i: Int => (k, JsNumber(i))
case l: Long => (k, JsNumber(l))
case f: Float => (k, JsNumber(f))
case d: Double => (k, JsNumber(d))
}): _*))
)
case d: Metrics => noneIfError[JsObject]((d.name, JsObject(export(d.values): _*)))
})
def noneIfError[A](f: => (String, A)): Option[(String, A)] = Try(f) match {
case Success(s) => Some(s)
case Failure(t) => None
}
}
示例6: VizRecJsonProtocol
//设置package包名称以及导入依赖的类
package com.lavsurgut.vizr.specs.vizrec
import spray.json.{DefaultJsonProtocol, DeserializationException, JsArray, JsObject, JsString, JsValue, JsonFormat, RootJsonFormat, _}
object VizRecJsonProtocol extends DefaultJsonProtocol {
implicit object FieldFormat extends JsonFormat[Field] {
def write(c: Field) =
JsObject(
Seq(
Some("channel" -> c.channel.toString.toJson),
Some("type" -> c.`type`.toString.toJson),
c.aggregate.map(aggregate => "aggregate" -> aggregate.toString.toJson),
c.field.map(field => "field" -> field.toJson),
c.timeUnit.map(timeUnit => "timeUnit" -> timeUnit.toString.toJson)
).flatten: _*
)
def read(value: JsValue) = {
value.asJsObject.getFields("channel", "type") match {
case Seq(JsString(channel), JsString(ttype)) =>
new Field(
channel = Channel.withName(channel),
`type` = Type.withName(ttype),
aggregate = value.asJsObject.fields.get("aggregate").map(v => Aggregate.withName(v.convertTo[String])),
field = value.asJsObject.fields.get("field").map(v => v.convertTo[String]),
timeUnit = value.asJsObject.fields.get("timeUnit").map(v => TimeUnit.withName(v.convertTo[String]))
)
case _ => throw new DeserializationException("Field spec expected")
}
}
}
implicit object VizRecSpecFormat extends RootJsonFormat[VizRecSpec] {
def write(c: VizRecSpec) = JsObject(
"mark" -> JsString(c.mark.toString),
"fields" -> JsArray(c.fields.map(f => FieldFormat.write(f)).toVector)
)
def read(value: JsValue) = {
value.asJsObject.getFields("mark", "fields") match {
case Seq(JsString(mark), JsArray(fields)) =>
new VizRecSpec(Mark.withName(mark), fields.map(f => FieldFormat.read(f)).toSeq)
case _ => throw new DeserializationException("VizRec spec expected")
}
}
}
}
示例7: GetEntriesHandler
//设置package包名称以及导入依赖的类
package in.lambda_hc.furious_cyclist.rest.handlers.entries
import in.lambda_hc.furious_cyclist.connectors.MysqlClient
import in.lambda_hc.furious_cyclist.models.EntryModel
import in.lambda_hc.furious_cyclist.utils.UNDERTOW_HELPERS
import io.undertow.server.{HttpServerExchange, HttpHandler}
import spray.json.{JsArray, JsString, JsObject}
import collection.JavaConversions._
class GetEntriesHandler extends HttpHandler {
override def handleRequest(exchange: HttpServerExchange): Unit = {
exchange.getResponseHeaders
.add(UNDERTOW_HELPERS.ACCESS_CONTROL_ALLOW_HEADERS._1, UNDERTOW_HELPERS.ACCESS_CONTROL_ALLOW_HEADERS._2)
.add(UNDERTOW_HELPERS.ACCESS_CONTROL_ALLOW_CREDENTIALS._1, UNDERTOW_HELPERS.ACCESS_CONTROL_ALLOW_CREDENTIALS._2)
.add(UNDERTOW_HELPERS.ACCESS_CONTROL_ALLOW_METHODS._1, UNDERTOW_HELPERS.ACCESS_CONTROL_ALLOW_METHODS._2)
.add(UNDERTOW_HELPERS.ACCESS_CONTROL_MAX_AGE._1, UNDERTOW_HELPERS.ACCESS_CONTROL_MAX_AGE._2)
val queryParams = exchange.getQueryParameters.map(i => {
(i._1, if (i._2.nonEmpty) i._2.getFirst else null)
}).toMap
val whereQuery = Array(
{
val v = queryParams.getOrElse("fromUser", null)
if (v != null) "userId=" + v else null
}, {
val v = queryParams.getOrElse("startDate", null)
if (v != null) "registeredDate>='" + v + "' " else null
}, {
val v = queryParams.getOrElse("endDate", null)
if (v != null) "registeredDate<='" + v + "' " else null
}, {
val v = queryParams.getOrElse("vehicle", null)
if (v != null) "vehicle=" + v else null
}, {
val v = queryParams.getOrElse("city", null)
if (v != null) "city='" + v + "'" else null
}
).filter(_ != null).mkString(" AND ")
val rs = MysqlClient.getResultSet("select * from entries " + (if (whereQuery.nonEmpty) "where " + whereQuery else ""))
val buf = scala.collection.mutable.ListBuffer.empty[JsObject]
while (rs.next()) {
buf += EntryModel.getFromResultSet(rs).toJson
}
exchange.getResponseSender.send(
JsObject(
"status" -> JsString("ok"),
"entries" -> JsArray(buf.toVector)
).prettyPrint
)
}
}
示例8: Extraction
//设置package包名称以及导入依赖的类
package org.karps.ops
import org.apache.spark.sql.types.StructType
import org.karps.{ColumnWithType, DataFrameWithType}
import org.karps.structures.{AugmentedDataType, IsNullable, IsStrict, JsonSparkConversions}
import org.karps.structures.JsonSparkConversions._
import spray.json.{JsArray, JsString, JsValue}
import scala.util.{Failure, Success, Try}
object Extraction {
import JsonSparkConversions.sequence
case class FieldName(name: String)
case class FieldPath(path: List[FieldName])
def getFieldPath(jsValue: JsValue): Try[FieldPath] = jsValue match {
case JsArray(arr) => sequence(arr.toList.map {
case JsString(s) => Success(FieldName(s))
case x => Failure(new Exception(s"Expected string, got $x"))
}) .map(x => FieldPath(x.toList))
case x => Failure(new Exception(s"Expected array, got $x"))
}
def extractCol(col: ColumnWithType, fp: FieldPath): Try[ColumnWithType] = {
fp match {
case FieldPath(Seq()) => Success(col)
case FieldPath(h :: t) =>
for {
col2 <- extractField(col, h)
col3 <- extractCol(col2, FieldPath(t))
} yield col3
}
}
def extractCol(adf: DataFrameWithType, fp: FieldPath): Try[ColumnWithType] = {
extractCol(DataFrameWithType.asTypedColumn(adf), fp)
}
def extractField(col: ColumnWithType, name: FieldName): Try[ColumnWithType] = {
col.rectifiedSchema.dataType match {
case s: StructType =>
s.fields.find(_.name == name.name) match {
case Some(f) =>
val nl = if (col.rectifiedSchema.isNullable || f.nullable) IsNullable else IsStrict
Success(ColumnWithType(col.col.getField(name.name), AugmentedDataType(f.dataType, nl)
, col.ref))
case None =>
Failure(new Exception(s"Cannot find field $name in $col"))
}
case _ =>
Failure(new Exception(s"Cannot find field $name in $col"))
}
}
}
示例9: DiagramLabel
//设置package包名称以及导入依赖的类
package org.allenai.dqa.labeling
import scala.io.Source
import spray.json.DefaultJsonProtocol._
import spray.json.JsArray
import spray.json.JsNumber
import spray.json.JsObject
import spray.json.deserializationError
import spray.json.pimpString
import scala.util.Random
case class DiagramLabel(diagramType: String, partLabels: Vector[String])
object Diagram {
def fromJsonFile(filename: String, features: Map[String, DiagramFeatures]
): Array[(Diagram, DiagramLabel)] = {
val lines = Source.fromFile(filename).getLines
lines.map(fromJsonLine(_, features)).toArray
}
def fromJsonLine(line: String, features: Map[String, DiagramFeatures]
): (Diagram, DiagramLabel) = {
val js = line.parseJson.asJsObject
val diagramLabel = js.fields("label").convertTo[String]
val diagramId = js.fields("id").convertTo[String]
val imageId = js.fields("imageId").convertTo[String]
val width = js.fields("width").convertTo[Int]
val height = js.fields("height").convertTo[Int]
// val pointJsons = Random.shuffle(js.fields("points").asInstanceOf[JsArray].elements)
val pointJsons = js.fields("points").asInstanceOf[JsArray].elements
val labeledParts = for {
(pointJson, i) <- pointJsons.zipWithIndex
p = pointJson.asJsObject
id = p.fields("textId").convertTo[String]
label = p.fields("label").convertTo[String]
xy = p.fields("xy") match {
case JsArray(Vector(JsNumber(x), JsNumber(y))) => Point(x.toInt, y.toInt)
case _ => deserializationError("Array of x/y coordinates expected")
}
} yield {
(Part(id, i, xy), label)
}
val f = features(imageId)
(Diagram(diagramId, imageId, width, height, labeledParts.map(_._1), f),
(DiagramLabel(diagramLabel, labeledParts.map(_._2))))
}
}
示例10: AddedNodeInfoMarshaller
//设置package包名称以及导入依赖的类
package org.bitcoins.rpc.marshallers.networking
import akka.http.scaladsl.model.Uri
import org.bitcoins.rpc.bitcoincore.networking.{AddedNodeInfo, NodeAddress}
import spray.json.{DefaultJsonProtocol, JsArray, JsBoolean, JsObject, JsString, JsValue, RootJsonFormat}
import NodeAddressMarshaller._
import org.bitcoins.core.util.BitcoinSLogger
object AddedNodeInfoMarshaller extends DefaultJsonProtocol with BitcoinSLogger {
val addedNodeKey = "addednode"
val connectedKey = "connected"
val addressesKey = "addresses"
implicit object AddedNodeInfoFormatter extends RootJsonFormat[AddedNodeInfo] {
override def read(value: JsValue): AddedNodeInfo = {
val obj = value.asJsObject
val f = obj.fields
val addedNode = Uri(f(addedNodeKey).convertTo[String])
val connected = f(connectedKey).convertTo[Boolean]
val addressesArray = f(addressesKey).asInstanceOf[JsArray]
val addresses = addressesArray.elements.map(a => a.convertTo[NodeAddress])
AddedNodeInfo(addedNode,connected,addresses)
}
override def write(nodeInfo: AddedNodeInfo): JsValue = {
val addresses: JsArray = JsArray(nodeInfo.addresses.map(n => JsString(n.toString)).toVector)
val m: Map[String,JsValue] = Map(
addedNodeKey -> JsString(nodeInfo.addedNode.toString),
connectedKey -> JsBoolean(nodeInfo.connected),
addressesKey -> addresses
)
JsObject(m)
}
}
}
示例11: FundRawTransactionOptionsMarshaller
//设置package包名称以及导入依赖的类
package org.bitcoins.rpc.marshallers.wallet
import org.bitcoins.rpc.bitcoincore.wallet.FundRawTransactionOptions
import spray.json.{DefaultJsonProtocol, JsArray, JsBoolean, JsNumber, JsObject, JsString, JsValue, RootJsonFormat}
object FundRawTransactionOptionsMarshaller extends DefaultJsonProtocol {
val changeAddressKey = "changeAddress"
val changePositionKey = "changePosition"
val includeWatchingKey = "includeWatching"
val lockUnspentKey = "lockUnspent"
val reserveChangeKeyKey = "reserveChangeKey"
val feeRateKey = "feeRate"
val subtractFeeFromOutputsKey = "subtractFeeFromOutputs"
implicit object FundRawTransactionOptionsFormatter extends RootJsonFormat[FundRawTransactionOptions] {
override def read(value: JsValue): FundRawTransactionOptions = {
//TODO: implement
???
}
override def write(options: FundRawTransactionOptions): JsValue = {
val withChangeAddress: Map[String,JsValue] = if (options.changeAddress.isDefined) {
Map(changeAddressKey -> JsString(options.changeAddress.get.value))
} else Map()
val withChangePos = if (options.changePosition.isDefined) {
withChangeAddress.updated(changePositionKey, JsNumber(options.changePosition.get))
} else withChangeAddress
val withIncludeWatchingKey = if (options.includeWatching.isDefined) {
withChangePos.updated(includeWatchingKey,JsBoolean(options.includeWatching.get))
} else withChangePos
val withLockUnspent = if (options.lockUnspent.isDefined) {
withIncludeWatchingKey.updated(lockUnspentKey,JsBoolean(options.lockUnspent.get))
} else withIncludeWatchingKey
val withReserveChangeKey = if (options.reserveChangeKey.isDefined) {
withLockUnspent.updated(reserveChangeKeyKey, JsBoolean(options.reserveChangeKey.get))
} else withLockUnspent
val withFeeRate = if (options.feeRate.isDefined) {
withReserveChangeKey.updated(feeRateKey, JsNumber(options.feeRate.get.underlying))
} else withReserveChangeKey
val withSubtractFeeFromOutputs = {
val arr = JsArray(options.subtractFeeFromOutputs.map(JsNumber(_)).toVector)
withFeeRate.updated(subtractFeeFromOutputsKey, arr)
}
JsObject(withSubtractFeeFromOutputs)
}
}
}
示例12: convertToJsArray
//设置package包名称以及导入依赖的类
package org.bitcoins.rpc.marshallers
import org.bitcoins.rpc.bitcoincore.blockchain.softforks.SoftForks
import org.bitcoins.rpc.bitcoincore.networking.{NetworkConnections, PeerInfo}
import org.bitcoins.rpc.marshallers.networking.NetworkConnectionsMarshaller.NetworkConnectionsFormatter
import org.bitcoins.rpc.marshallers.networking.PeerInfoRPCMarshaller.PeerInfoFormatter
import spray.json.{JsArray, JsValue, JsonWriter}
import scala.collection.breakOut
trait RPCMarshallerUtil {
def convertToJsArray[T](seq : Seq[T])(implicit formatter : JsonWriter[T]) : JsArray = {
JsArray(seq.map(p =>
formatter.write(p))(breakOut): Vector[JsValue])
}
def convertToPeerInfoSeq(value : JsValue) : Seq[PeerInfo] = {
value match {
case ja: JsArray => {
ja.elements.toList.map(
e => PeerInfoFormatter.read(e))
}
case _ => throw new RuntimeException("This Json type is not valid for parsing a list of peer info")
}
}
def convertToNetworkConnectionList(value : JsValue) : Seq[NetworkConnections] = {
value match {
case ja: JsArray => {
ja.elements.toList.map(
e => NetworkConnectionsFormatter.read(e))
}
case _ => throw new RuntimeException("This Json type is not valid for parsing a list of network connections")
}
}
}
示例13: sendRequest
//设置package包名称以及导入依赖的类
package org.bitcoins.rpc
import akka.http.javadsl.model.headers.HttpCredentials
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.stream.ActorMaterializer
import org.bitcoins.rpc.config.DaemonInstance
import spray.json.{JsArray, JsBoolean, JsNumber, JsObject, JsString, JsValue}
import scala.concurrent.Future
sealed trait RPCHandler {
def sendRequest(instance: DaemonInstance, jsObject: JsObject)(implicit m: ActorMaterializer): Future[HttpResponse] = {
val username = instance.authCredentials.username
val password = instance.authCredentials.password
val req = HttpRequest(method = HttpMethods.POST, uri = instance.rpcUri,
entity = HttpEntity(ContentTypes.`application/json`,jsObject.toString()))
.addCredentials(HttpCredentials.createBasicHttpCredentials(username,password))
sendRequest(req)
}
def sendRequest(req: HttpRequest)(implicit m: ActorMaterializer): Future[HttpResponse] = {
Http(m.system).singleRequest(req)
}
def buildRequest(methodName: String, param: Int): JsObject = {
buildRequest(methodName, JsArray(JsNumber(param)))
}
def buildRequest(methodName: String, param: String): JsObject = {
buildRequest(methodName,JsArray(JsString(param)))
}
def buildRequest(methodName: String, param: Boolean): JsObject = {
buildRequest(methodName, JsArray(JsBoolean(param)))
}
def buildRequest(methodName: String, params: JsArray): JsObject = {
val m : Map[String,JsValue] = Map(
"method" -> JsString(methodName),
"params" -> params,
"id" -> JsString(""))
JsObject(m)
}
def buildRequest(methodName: String): JsObject = {
buildRequest(methodName,JsArray(Vector()))
}
def buildRequest(methodName: String, param1: String, opt: JsObject): JsObject = {
val arr = JsArray(JsString(param1),opt)
buildRequest(methodName,arr)
}
}
object RPCHandler extends RPCHandler
示例14: MarshallerUtilTest
//设置package包名称以及导入依赖的类
package org.bitcoins.marshallers
import org.bitcoins.marshallers.transaction.TransactionInputMarshaller.TransactionInputFormatter
import org.bitcoins.util.TestUtil
import org.scalatest.{FlatSpec, MustMatchers}
import spray.json.JsArray
class MarshallerUtilTest extends FlatSpec with MustMatchers with MarshallerUtil {
"MarshallerUtil" must "convert a sequence of something to a json array" in {
val inputs = TestUtil.simpleTransaction.inputs
val jsonInputs = convertToJsArray(inputs)(TransactionInputFormatter)
val isJsArray = jsonInputs match {
case j : JsArray => true
case _ => false
}
isJsArray must be (true)
}
}