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


Scala GsonBuilder类代码示例

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


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

示例1: ChannelHelper

//设置package包名称以及导入依赖的类
package us.illyohs.sinked.helper

import java.io.{File, FileWriter, IOException, Writer}
import java.util

import com.google.gson.{FieldNamingPolicy, Gson, GsonBuilder}
import org.spongepowered.api.Sponge
import us.illyohs.sinked.Sinked
import us.illyohs.sinked.channel.Channel

object ChannelHelper {

  val chanList:util.List[Channel] = new  util.ArrayList[Channel]()

  val sinked:Sinked = null
  val channelPath = "./channels/"

  val channelDir = new File(channelPath)

  def initChannel: Unit = {
    chanList.add(new GlobalChannel)
    chanList.add(new LocalChannel)
    if (!channelDir.exists()) {
      //      sinked.getLogger.warn("Channel directory not found!")
      //      sinked.getLogger.info("Now creating channel directory")

      channelDir.mkdir()
      val gson: Gson = new GsonBuilder()
        .setPrettyPrinting()
        .serializeNulls()
        .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
        .create()
      for (i <- 0 to 1) {
        val ch = chanList.get(i)
        val json = gson.toJson(ch)
        val w: Writer = new FileWriter(channelPath + ch.getName + ".json")
        try {
          w.write(json)
          w.close()
          //          sinked.getLogger.info("Created default channel: " +ch.getName)
        } catch {
          case e: IOException => e.printStackTrace()
        }
      }
      //      createDefualtjons
    }
  }


  case class GlobalChannel() extends Channel("Global", "", "G", "", "", false, true, false, false, true)
  case class LocalChannel() extends Channel("Local", "", "L", "", "", false, true, false, false, false)
} 
开发者ID:DragonTechMC,项目名称:Sinked,代码行数:53,代码来源:ChannelHelper.scala

示例2: TwitterStream

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

import com.google.gson.GsonBuilder
import org.apache.spark.storage.StorageLevel
import org.apache.spark.streaming.twitter.TwitterUtils
import org.apache.spark.streaming.{Minutes, StreamingContext}
import org.apache.spark.{Logging, SparkConf, SparkContext}
import twitter4j.auth.OAuthAuthorization
import twitter4j.conf.ConfigurationBuilder

import scala.util.Try

object TwitterStream extends SimpleConfig with Logging {

  def getTwitterStream(ssc: StreamingContext, filters: Seq[String] = Nil) = {
    val builder = new ConfigurationBuilder()
    builder.setOAuthConsumerKey(twitterApiKey)
    builder.setOAuthConsumerSecret(twitterApiSecret)
    builder.setOAuthAccessToken(twitterTokenKey)
    builder.setOAuthAccessTokenSecret(twitterTokenSecret)
    val configuration = builder.build()
    TwitterUtils.createStream(
      ssc,
      Some(new OAuthAuthorization(configuration)),
      filters,
      StorageLevel.MEMORY_ONLY
    )
  }

  def main(args: Array[String]) = {

    val sparkConf = new SparkConf().setAppName("Twitter Extractor")
    val sc = new SparkContext(sparkConf)
    val ssc = new StreamingContext(sc, Minutes(5))

    val twitterStream = getTwitterStream(ssc, args).mapPartitions({ it =>
      val gson = new GsonBuilder().create()
      it map { s =>
        Try(gson.toJson(s))
      }
    })

    twitterStream
      .filter(_.isSuccess)
      .map(_.get)
      .saveAsTextFiles("twitter")

    // Start streaming context
    ssc.start()
    ssc.awaitTermination()

  }

} 
开发者ID:PacktPublishing,项目名称:Mastering-Spark-for-Data-Science,代码行数:55,代码来源:TwitterStream.scala

示例3: SimpleConsumers

//设置package包名称以及导入依赖的类
package com.godatadriven.kafka.offset

import com.google.gson.{Gson, GsonBuilder}
import kafka.consumer.SimpleConsumer
import org.apache.zookeeper.ZooKeeper

import scala.collection.JavaConversions._

class SimpleConsumers(zookeeper: ZooKeeper) {
  val gson: Gson = new GsonBuilder().create()

  val children: Map[String, SimpleConsumer] = zookeeper.getChildren("/brokers/ids", false).map(id => {
    val brokerInfoJson: String = new String(zookeeper.getData("/brokers/ids/" + id, false, null))

    val brokerInfo = gson.fromJson(brokerInfoJson, classOf[BrokerInfo])
    id -> new SimpleConsumer(brokerInfo.getHost, brokerInfo.getPort, 10000, 100000, "consumerOffsetChecker")
  }).toMap

  def get(key: String): Option[SimpleConsumer] = {
    children.get(key)
  }

  def close(): Unit = {
    children.foreach(_._2.close())
  }
} 
开发者ID:godatadriven,项目名称:prometheus-kafka-offsets,代码行数:27,代码来源:SimpleConsumers.scala

示例4: BrokerInfoTest

//设置package包名称以及导入依赖的类
package com.godatadriven.kafka.offset

import com.google.gson.{Gson, GsonBuilder}
import org.apache.kafka.common.protocol.SecurityProtocol
import org.specs2.mutable.Specification

class BrokerInfoTest extends Specification {
  val gson: Gson = new GsonBuilder().create()

  "Brokerinfo host should" >> {
    "return host if host is filled" >> {
      val brokerInfo = gson.fromJson("{\"jmx_port\":-1,\"timestamp\":\"1459185255551\",\"host\":\"ron\",\"version\":1,\"port\":9092}", classOf[BrokerInfo])
      brokerInfo.getHost must equalTo("ron")
    }
    "return host if endpoint is filled" >> {
      val brokerInfo = gson.fromJson("{\"jmx_port\":-1,\"timestamp\":\"1459185255551\",\"endpoints\": [\"PLAINTEXTSASL://ron:9092\"],\"host\":\"\",\"version\":1,\"port\":-1}", classOf[BrokerInfo])
      brokerInfo.getHost must equalTo("ron")
    }
    "return host if endpoint is filled and host is null" >> {
      val brokerInfo = gson.fromJson("{\"jmx_port\":-1,\"timestamp\":\"1459185255551\",\"endpoints\": [\"PLAINTEXTSASL://ron:9092\"],\"host\": null,\"version\":1,\"port\":-1}", classOf[BrokerInfo])
      brokerInfo.getHost must equalTo("ron")
    }
  }

  "Brokerinfo port should" >> {
    "return port if port is filled" >> {
      val brokerInfo = gson.fromJson("{\"jmx_port\":-1,\"timestamp\":\"1459185255551\",\"host\":\"ron\",\"version\":1,\"port\":9092}", classOf[BrokerInfo])
      brokerInfo.getPort must equalTo(9092)
    }
    "return port if endpoinst is filled" >> {
      val brokerInfo = gson.fromJson("{\"jmx_port\":-1,\"timestamp\":\"1459185255551\",\"endpoints\": [\"PLAINTEXTSASL://ron:9092\"],\"host\":\"\",\"version\":1,\"port\":-1}", classOf[BrokerInfo])
      brokerInfo.getPort must equalTo(9092)
    }
  }

} 
开发者ID:godatadriven,项目名称:prometheus-kafka-offsets,代码行数:37,代码来源:BrokerInfoTest.scala

示例5: Notification

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

import java.text.DateFormat
import java.util

import com.rallets.{RUtils, Store}
import com.google.gson.{Gson, GsonBuilder}
import org.json.JSONObject

object Notification {
  private var  _one: Notification = new Notification
  val gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create()

  def one = _one
  def one_=(result: String) {
    _one = gson.fromJson(result, classOf[Notification])
  }
}

class Notification {
  var ok: Boolean = false
  var self: User = new User
  var goods: util.ArrayList[Good] = new util.ArrayList[Good]()
  var systemNotification = new SystemNotification
} 
开发者ID:rallets-network,项目名称:rallets-android,代码行数:26,代码来源:Notification.scala

示例6: JWKGenerator

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

import java.security.KeyPairGenerator
import java.security.interfaces.{RSAPrivateKey, RSAPublicKey}

import com.google.gson.{GsonBuilder, JsonElement, JsonParser}
import com.nimbusds.jose.Algorithm
import com.nimbusds.jose.jwk.{JWKSet, KeyUse, RSAKey}

object JWKGenerator {

  def make(keySize: Integer, keyUse: KeyUse, keyAlg: Algorithm, keyId: String) = {
    val generator = KeyPairGenerator.getInstance("RSA")
    generator.initialize(keySize)
    val kp = generator.generateKeyPair()
    val publicKey = kp.getPublic().asInstanceOf[RSAPublicKey]
    val privateKey = kp.getPrivate().asInstanceOf[RSAPrivateKey]
    new RSAKey.Builder(publicKey)
      .privateKey(privateKey)
      .keyUse(keyUse)
      .algorithm(keyAlg)
      .keyID(keyId)
      .build()
  }

  
  def generateJWKJson(rsaKey: RSAKey): String = {
    val jsonElement  = generateJWKKeypair(rsaKey)
    val gson = new GsonBuilder().setPrettyPrinting().create()
    gson.toJson(jsonElement)
  }


} 
开发者ID:bijukunjummen,项目名称:test-nimbus-jose-jwt,代码行数:35,代码来源:JWKGenerator.scala

示例7: WeiboyiListProcessor

//设置package包名称以及导入依赖的类
package org.webant.plugin.weiboyi.processor

import com.google.gson.{GsonBuilder, JsonParser}
import org.webant.commons.utils.DateFormatUtils
import org.webant.plugin.weiboyi.data.WeiboyiDetailData
import org.webant.worker.processor.JsonPageProcessor

class WeiboyiListProcessor extends JsonPageProcessor[WeiboyiDetailData] {
  regex = "http://chuanbo.weiboyi.com/hworder/weixin/filterlist/source/all\\?start=\\d*&limit=\\d*"

  private val gson = new GsonBuilder().setDateFormat(DateFormatUtils.DATE_TIME_FORMAT).create()

  override protected def list(): Iterable[WeiboyiDetailData] = {
    val parser = new JsonParser
    val result = parser.parse(content).getAsJsonObject
    if (!result.has("data"))
      return Iterable.empty
    val data = result.getAsJsonObject("data")
    if (!data.has("rows"))
      return Iterable.empty

    val rows = data.get("rows").getAsJsonArray
    val list = (0 until rows.size()).map(index => {
      val item = rows.get(index).getAsJsonObject
      val srcId = item.get("id").getAsLong
      val json = item.get("cells").toString
      val data = gson.fromJson(json, classOf[WeiboyiDetailData])
      data.id = srcId.toString
      data.srcId = srcId.toString
      data.source = "weiboyi.com"
      data
    })
    list
  }
} 
开发者ID:sutine,项目名称:webant-workbench,代码行数:36,代码来源:WeiboyiListProcessor.scala

示例8: GsonScalaRegistrator

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

import com.google.gson.GsonBuilder

package object gsonscala {
  implicit class GsonScalaRegistrator(val gsonBuilder: GsonBuilder) extends AnyVal {

    def registerBasicConverters(): GsonBuilder = gsonBuilder
      .registerTypeAdapterFactory(OptionalTypeAdapterFactory)
      .registerTypeAdapterFactory(OptionTypeAdapterFactory)
      .registerTypeAdapterFactory(SeqTypeAdapterFactory)
      .registerTypeAdapterFactory(NonNullTypeAdapterFactory)

    def registerStringDurationConverters(): GsonBuilder = gsonBuilder
      .registerTypeAdapter(classOf[java.time.Duration], DurationAsStringConverter)
      .registerTypeHierarchyAdapter(classOf[scala.concurrent.duration.Duration], ScalaDurationAsStringConverter)

    def registerMillisDurationConverters(): GsonBuilder = gsonBuilder
      .registerTypeAdapter(classOf[java.time.Duration], DurationAsMillisConverter)
      .registerTypeHierarchyAdapter(classOf[scala.concurrent.duration.Duration], ScalaDurationAsMillisConverter)

    def registerSecondsDurationConverters(): GsonBuilder = gsonBuilder
      .registerTypeAdapter(classOf[java.time.Duration], DurationAsSecondsConverter)
      .registerTypeHierarchyAdapter(classOf[scala.concurrent.duration.Duration], ScalaDurationAsSecondsConverter)

    def registerStringInstantConverter(): GsonBuilder = gsonBuilder.registerTypeAdapter(classOf[java.time.Instant], InstantAsStringConverter)
    def registerUnixMillisInstantConverter(): GsonBuilder = gsonBuilder.registerTypeAdapter(classOf[java.time.Instant], InstantAsUnixMillisConverter)
    def registerUnixSecondsInstantConverter(): GsonBuilder = gsonBuilder.registerTypeAdapter(classOf[java.time.Instant], InstantAsUnixSecondsConverter)

  }
} 
开发者ID:augi,项目名称:gson-scala,代码行数:32,代码来源:package.scala

示例9: JsonOutPut

//设置package包名称以及导入依赖的类
package ar.edu.unq.tpi.qsim.integracion.mumuki

import com.google.gson.GsonBuilder
import ar.edu.unq.tpi.qsim.model._
import java.lang.reflect._
import com.google.gson.reflect._

abstract class JsonOutPut
case class JsonQ(var id: Int, var special_records: SpecialRecords, var flags: Flags, var records: Records, var memory: java.util.Map[String, String]) extends JsonOutPut
case class SpecialRecords(val PC: String, val SP: String, val IR: String) extends JsonOutPut
case class Flags(val N: Int, val Z: Int, val V: Int, val C: Int) extends JsonOutPut
case class Records(val R0: String, val R1: String, val R2: String, val R3: String, val R4: String,
                   val R5: String, val R6: String, val R7: String) extends JsonOutPut
case class JsonError(val id: Int, val error: String, val kind: String) extends JsonOutPut

class JsonResult {

  implicit def registroToString(registro: Registro): String = registro.valor.hex
  var gson = new GsonBuilder().setPrettyPrinting().create()
  val listType : Type = new TypeToken[java.util.List[JsonQ]]() {}.getType()
    

  def buildJsonOk(sim: Simulador) =
    JsonQ(sim.inputExeActual,
      SpecialRecords(sim.cpu.pc.hex, sim.cpu.sp.hex, sim.cpu.ir),
      Flags(sim.cpu.n, sim.cpu.z, sim.cpu.v, sim.cpu.c),
      Records(sim.cpu.registros(0), sim.cpu.registros(1), sim.cpu.registros(2), sim.cpu.registros(3), sim.cpu.registros(4),
        sim.cpu.registros(5), sim.cpu.registros(6), sim.cpu.registros(7)),
      sim.busIO.stateMemory)

  def parserJson(json: String) : java.util.List[JsonQ] = {
     gson.fromJson(json, listType)
  }
} 
开发者ID:Orga-UNQ,项目名称:qsim,代码行数:35,代码来源:IntegracionMumuki.scala

示例10: runMainMumuki

//设置package包名称以及导入依赖的类
package ar.edu.unq.tip.qsim.integracion.mumuki

import com.google.gson.GsonBuilder

object runMainMumuki extends App {

  val program = args(0)
  val arqQ = args(1).toInt - 1
  val input = args(2)
  val gson = new GsonBuilder().setPrettyPrinting().create()

  val multExe = new MultExecutor()
  val outputs = multExe.exeInputs(program, arqQ, input)
  Console.println(gson.toJson(outputs))
  System.exit(0)
} 
开发者ID:Orga-UNQ,项目名称:qsim,代码行数:17,代码来源:RunQsimMumuki.scala

示例11: LocalStoreTest

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

import java.time.{ZoneId, ZonedDateTime => Time}

import adapter.bitflyer.realtime.TestData
import application.Validations
import com.google.gson.{FieldNamingPolicy, GsonBuilder}
import domain.TimeKeeper
import org.scalatest.{BeforeAndAfterAll, FunSuite}
import testutil.TimeTestHelper

class LocalStoreTest extends FunSuite with BeforeAndAfterAll {

  val now = Time.of(2017, 7, 12 ,4, 30, 14, 11, ZoneId.of("UTC"))
  val sample = new TestData()
  val gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create
  val testing: LocalStore = new LocalStore("LocalStoreTestDummyFile", new TimeKeeper(1, TimeTestHelper.of(2017, 5, 5, 0, 0, 0, 0)))

  override def beforeAll() = Validations.workingDirectoryExisits
  override def afterAll() = testing.delete()

  test("test create & delete") {
    val st = new LocalStore("LocalStoreTestDummy2File")
    assert(st.exists === true)
    st.delete
    assert(st.exists === false)
  }

  test("file name") {
    assert(testing.fileName.replace("LocalStoreTestDummyFile","").size > 0)
  }

  test("testWriteJson") {
    val json = gson.toJsonTree(sample.tickerInfo())
    testing.writeJson(json)

    val lines = testing.lines()
    assert(lines.size === 1)
    assert(lines.mkString("").contains("product_code"))
  }

  test("testStore") {
    testing.write() match {
      case Right(newStore) => assert(newStore !== testing)
      case Left(_) => fail()
    }
  }
} 
开发者ID:rysh,项目名称:scalatrader,代码行数:49,代码来源:LocalStoreTest.scala


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