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


Scala Gson类代码示例

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


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

示例1: wrapperObject

//设置package包名称以及导入依赖的类
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser

case class wrapperObject(val json_string: Array[MyJsonObject])
case class MyJsonObject(val id:Int ,val price:Int)

object JsonParsing {
  
    def maxVal():Integer = {
      
        val json_string = scala.io.Source.fromFile("jsonData1.json").getLines.mkString
        val jsonStringAsObject= new JsonParser().parse(json_string).getAsJsonObject
        val myObj:wrapperObject = gson.fromJson(jsonStringAsObject, classOf[wrapperObject])
        var maxPrice:Int = 0
        for(i <- myObj.json_string if i.price > maxPrice) 
        {
            maxPrice=  i.price
        }
        return maxPrice
    }
  
    def time[R](block: => R): R = {  
        val t0 = System.nanoTime()
        val result = block    // call-by-name
        val t1 = System.nanoTime()
        println("Elapsed time: " + (t1 - t0) + "ns")
        result
    }

    val gson = new Gson()
    
    def main(args: Array[String]): Unit = {
       
      time{println(maxVal())}
      
      val runtime = Runtime.getRuntime
      println("Used Memory:  " + (runtime.totalMemory - runtime.freeMemory))    
    }
} 
开发者ID:vinzee,项目名称:language_comparison,代码行数:41,代码来源:JsonParsing.scala

示例2: MCWhitelistHelper

//设置package包名称以及导入依赖的类
package com.amadornes.modcast.bot.helpers

import java.net.URLEncoder

import com.amadornes.modcast.bot.Actors
import com.amadornes.modcast.bot.database.{DB, UserMCAccount}
import com.amadornes.modcast.bot.servers.MCWhitelistServer
import com.google.gson.{Gson, JsonObject}
import sx.blah.discord.handle.obj.IUser

import scalaj.http.Http


object MCWhitelistHelper {
	def associateMCAccountWithUser(user: IUser, account: String): Unit = {
		val id = getMCAccountUUID(account)
		if (DB.query[UserMCAccount].whereEqual("user", user.getID).exists())
			deassociateMCAccountWithUser(user)
		Actors.servers.MCWhitelistServer ! MCWhitelistServer.WhitelistUser(id)
		DB.save(UserMCAccount(user.getID, id))
	}
	
	def deassociateMCAccountWithUser(user: IUser): Unit = {
		val account = DB.query[UserMCAccount].whereEqual("user", user.getID).fetchOne()
		if (account.isDefined) {
			Actors.servers.MCWhitelistServer ! MCWhitelistServer.UnWhitelistUser(account.get.account)
			DB.delete(account.get)
		}
	}
	
	def getMCAccountUUID(name: String): String = {
		val http = Http("http://mcapi.ca/profile/" + URLEncoder.encode(name)).asString
		if (http.code != 200)
			throw new IllegalArgumentException()
		new Gson().fromJson(http.body, classOf[JsonObject]).get("uuid_formatted").getAsString
	}
} 
开发者ID:Modcast,项目名称:ModcastBot,代码行数:38,代码来源:MCWhitelistHelper.scala

示例3: Collector

//设置package包名称以及导入依赖的类
package com.databricks.apps.twitterClassifier

import com.google.gson.Gson
import org.apache.spark.SparkContext
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.dstream.DStream
import org.apache.spark.streaming.twitter.TwitterUtils


object Collector {
  def doIt(options: CollectOptions, sc: SparkContext, ssc: StreamingContext) {
    val tweetStream: DStream[String] = TwitterUtils.createStream(ssc, maybeTwitterAuth)
      .map(new Gson().toJson(_))

    var numTweetsCollected = 0L
    tweetStream.foreachRDD { (rdd, time) =>
      val count = rdd.count
      if (count > 0) {
        rdd.saveAsTextFile(options.tweetDirectory.getAbsolutePath)
        numTweetsCollected += count
        if (numTweetsCollected > options.numTweetsToCollect) System.exit(0)
      }
    }

    ssc.start()
    ssc.awaitTermination()
  }
} 
开发者ID:krish121,项目名称:Spark-reference-applications,代码行数:29,代码来源:Collect.scala

示例4: WarmupZeppelin

//设置package包名称以及导入依赖的类
package biz.meetmatch.modules.util

import biz.meetmatch.modules.Module
import biz.meetmatch.util.Utils
import com.google.gson.Gson
import org.apache.spark.sql.SparkSession
import org.rogach.scallop.Scallop
import org.slf4j.LoggerFactory

import scalaj.http.Http

object WarmupZeppelin extends Module {

  override def execute(scallopts: Scallop)(implicit sparkSession: SparkSession): Unit = {
    val interpreterId = Utils.getConfig("zeppelin.interpreter.id")

    logger.info(s"Restarting the spark interpreter using url http://localhost:8080/api/interpreter/setting/restart/$interpreterId...")
    val interpreterResponse = Http(s"http://localhost:8080/api/interpreter/setting/restart/$interpreterId")
      .method("put")
      .timeout(connTimeoutMs = 10000, readTimeoutMs = 60000)
      .asParamMap
    logger.info("Response code: " + interpreterResponse.code)

    if (interpreterResponse.code == 200) {
      val bootstrapNotebookId = Utils.getConfig("zeppelin.bootstrapNotebookId.id")

      logger.info(s"Executing the Bootstrap notebook using url http://localhost:8080/api/notebook/job/$bootstrapNotebookId...")
      val notebookResponse = Http(s"http://localhost:8080/api/notebook/job/$bootstrapNotebookId")
        .postForm
        .timeout(connTimeoutMs = 10000, readTimeoutMs = 60000)
        .asParamMap
      logger.info("Response code: " + notebookResponse.code)

      if (notebookResponse.code == 200) {
        def stillRunningParagraphs(): Boolean = {
          logger.info("Checking if the Bootstrap notebook has finished...")
          val checkNotebookResponse = Http("http://localhost:8080/api/notebook/job/2BKFC4D5W")
            .timeout(connTimeoutMs = 10000, readTimeoutMs = 120000)
            .asString
          logger.info("Response code: " + checkNotebookResponse.code)
          val notebookJobResponse = new Gson().fromJson(checkNotebookResponse.body, classOf[GetNotebookJobResponse])
          notebookJobResponse.body.exists(_.status != "FINISHED")
        }

        while (stillRunningParagraphs()) {
          logger.info("Keep on polling...")
          Thread.sleep(5000)
        }
        logger.info("The Bootstrap notebook has finished.")
      }
    }
  }

  case class GetNotebookJobResponse(status: String, body: Array[ParagraphStatus])

  case class ParagraphStatus(id: String, started: String, finished: String, status: String)

  override protected val logger = LoggerFactory.getLogger(this.getClass)
} 
开发者ID:tolomaus,项目名称:languagedetector,代码行数:60,代码来源:WarmupZeppelin.scala

示例5: 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

示例6: NetCDF

//设置package包名称以及导入依赖的类
package se.kth.climate.fast.netcdf

import se.kth.climate.fast.common.Metadata
import se.kth.climate.fast.netcdf.hadoop._
import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD
import org.apache.spark.storage.StorageLevel
import com.typesafe.scalalogging.LazyLogging
import scala.concurrent.Future
import scala.concurrent.ExecutionContext
import com.google.gson.Gson
import ucar.nc2.NetcdfFile

object NetCDF extends LazyLogging {
  def metaDataAsync(path: String)(implicit sc: SparkContext, ec: ExecutionContext): Future[Metadata] = {
    Future {
      NetCDF.metaData(path)
    }
  }

  def metaData(path: String)(implicit sc: SparkContext): Metadata = {
    val metaSRDD = sc.textFile(path + "/metadata.json", 1);
    val metaS = metaSRDD.collect().mkString;
    val gson = new Gson();
    gson.fromJson(metaS, classOf[Metadata]);
  }

  def rawData(path: String)(implicit sc: SparkContext): RDD[NetcdfFile] = {
    val rdd = sc.newAPIHadoopFile[Void, NCWritable, NetCDFFileFormat](path)
    val ncrdd = rdd.map {
      case (_, v) => {
        val ncfile = v.get;
        //ncfile.setImmutable(); // can't write them out, so don't let anyone mutate them
        ncfile
      }
    }
    //ncrdd.persist(StorageLevel.MEMORY_ONLY_SER);
    ncrdd.cache();
    ncrdd
  }
} 
开发者ID:ClimateFAST,项目名称:FASTSpark,代码行数:42,代码来源:NetCDF.scala

示例7: PersonApiTest

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

import com.google.gson.Gson
import conf.security.AuthUtil
import conf.util.Util
import domain.persons.Person
import org.specs2.mutable._
import org.specs2.runner._
import org.junit.runner._
import play.api.Logger
import play.api.libs.json.Json

import play.api.test._
import play.api.test.Helpers._
import scala.concurrent.ExecutionContext.Implicits.global

@RunWith(classOf[JUnitRunner])
class PersonApiTest extends Specification{



  val gson = new Gson()

  val person = Person(
    "HASHCODE",
    Util.md5Hash("hashvalue"),
    "ADMIN",
    "[email protected]",
    "USER",
    AuthUtil.encode("admin"),
    true,
    true,
    true,
    true,
    "ACTIVE")

  val jsonstring = gson.toJson(person).stripMargin

  val json = Json.parse(jsonstring)


  "render the index page" in new WithApplication{
    val home = route(FakeRequest(POST, "/api/people/post").withJsonBody(json)).get

//    status(home) must equalTo(OK)
//    contentType(home) must beSome.which(_ == "text/html")
//    contentAsString(home) must contain ("Your new application is ready.")
    println(" The Object is ", json)
  }

} 
开发者ID:Thulebona,项目名称:hashpvtapi,代码行数:52,代码来源:PersonApiTest.scala

示例8: RelationFace

//设置package包名称以及导入依赖的类
package pl.writeonly.babel.swt.faces

import org.eclipse.jface.viewers.TableViewer
import org.eclipse.swt.widgets.Display
import org.eclipse.swt.widgets.Table
import com.coconut_palm_software.xscalawt.viewers.TableViewerBuilder
import com.weiglewilczek.slf4s.Logging
import javax.annotation.Resource
import pl.writeonly.babel.beans.RecordBean
import pl.writeonly.babel.beans.RelationBean
import pl.writeonly.babel.beans.WordBean
import pl.writeonly.babel.entities.Relation
import pl.writeonly.babel.swt.Face
import pl.writeonly.babel.swt.FaceBuilder
import pl.writeonly.babel.swt.cards.RelationCard
import pl.writeonly.babel.swt.providers.RelationTableProvider
import pl.writeonly.scala.util.SingleAbstractMethod._
import com.google.gson.Gson
import java.util.Arrays
import pl.writeonly.babel.swt.Facade

@org.springframework.stereotype.Controller
class RelationFace extends FaceBuilder[Relation] {
  @Resource var relationService: RelationBean = _
  @Resource var tableProvider: RelationTableProvider = _
  @Resource var recordService: RecordBean = _
  @Resource var parseService: ParseBean = _
  @Resource var facade: Facade = _

  def apply() = RelationCard(this)

  def insert = relationService.persistAll (check())
  //  def find = try { addAll(relationService.find) } catch { case e: RuntimeException => runtime(e)}
  def recordAll = recordService.toRecordAll(check())
  def find = clear.addAll(relationService.find)
  def toJson = logger debug new Gson().toJson(Arrays.asList(tableProvider.array))
  def deen = parseService.deen (facade.open.getFileName())

  protected def clear() = { builder.table.clearAll(); this }
  def addAll(list: List[Relation]) {
    logger debug "addAll list => " + list
    tableProvider.add(list.toArray)
    Display.getDefault.syncExec { list.foreach(builder.viewer.add(_)) }
  }
} 
开发者ID:writeonly,项目名称:babel,代码行数:46,代码来源:RelationFace.scala

示例9: 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

示例10: 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

示例11: StorageUrlControllerTest

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

import com.google.gson.Gson
import domain.storage.StorageUrl
import org.scalatestplus.play.{OneAppPerTest, PlaySpec}
import play.api.libs.json.Json
import play.api.test.FakeRequest
import play.api.test.Helpers._


class StorageUrlControllerTest extends PlaySpec with OneAppPerTest {
  val gson = new Gson()
  val storageUrl = StorageUrl(
    "SIT52",
    "458K",
    "Triu",
    "https://zi.com")

  "Routes" should {
    "StorageUrlController" should {

      "Create StorageUrl Object in Through Controller" in {
        val request = route(app, FakeRequest(POST, "/storageUrl/create")
          .withJsonBody(Json.toJson(storageUrl)))
          .get
        status(request) mustBe OK
        contentType(request) mustBe Some("application/json")
        println(" The Content is ", contentAsString(request))
      }

      "Get StorageUrl From Controller" in {
        val request = route(app, FakeRequest(GET, "/storageUrl/")
        ).get
        status(request) mustBe OK
        contentType(request) mustBe Some("application/json")
        println(" The Output", contentAsJson(request))
      }
    }
  }
} 
开发者ID:boniface,项目名称:hworkapi,代码行数:41,代码来源:StorageUrlControllerTest.scala

示例12: FileMetaControllerTest

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

import com.google.gson.Gson
import domain.storage.FileMeta
import org.scalatestplus.play.{OneAppPerTest, PlaySpec}
import play.api.libs.json.Json
import play.api.test.FakeRequest
import play.api.test.Helpers._


class FileMetaControllerTest extends PlaySpec with OneAppPerTest {
  val gson = new Gson()
  val fileMeta = FileMeta(
    "SIT52",
    "Mozulla",
    "Triupa")

  "Routes" should {
    "FileMetaController" should {

      "Create FileMeta Object in Through Controller" in {
        val request = route(app, FakeRequest(POST, "/fileMeta/create")
          .withJsonBody(Json.toJson(fileMeta)))
          .get
        status(request) mustBe OK
        contentType(request) mustBe Some("application/json")
        println(" The Content is ", contentAsString(request))
      }

      "Get FileMeta From Controller" in {
        val request = route(app, FakeRequest(GET, "/fileMeta/")
        ).get
        status(request) mustBe OK
        contentType(request) mustBe Some("application/json")
        println(" The Output", contentAsJson(request))
      }
    }
  }
} 
开发者ID:boniface,项目名称:hworkapi,代码行数:40,代码来源:FileMetaControllerTest.scala

示例13: FileResultsControllerTest

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

import com.google.gson.Gson
import domain.storage.FileResults
import org.scalatestplus.play.{OneAppPerTest, PlaySpec}
import play.api.libs.json.Json
import play.api.test.FakeRequest
import play.api.test.Helpers._



class FileResultsControllerTest extends PlaySpec with OneAppPerTest {
  val gson = new Gson()
  val fileResults = FileResults(
    "SIT52",
    "MO47",
    "https://tri.com",
    Option("Triupa"))

  "Routes" should {
    "FileResultsController" should {

      "Create FileResults Object in Through Controller" in {
        val request = route(app, FakeRequest(POST, "/fileResults/create")
          .withJsonBody(Json.toJson(fileResults)))
          .get
        status(request) mustBe OK
        contentType(request) mustBe Some("application/json")
        println(" The Content is ", contentAsString(request))
      }

      "Get FileResults From Controller" in {
        val request = route(app, FakeRequest(GET, "/fileResults/")
        ).get
        status(request) mustBe OK
        contentType(request) mustBe Some("application/json")
        println(" The Output", contentAsJson(request))
      }
    }
  }
} 
开发者ID:boniface,项目名称:hworkapi,代码行数:42,代码来源:FileResultsControllerTest.scala

示例14: UserImagesControllerTest

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

import com.google.gson.Gson
import domain.users.UserImages
import org.joda.time.DateTime
import org.scalatestplus.play.{OneAppPerTest, PlaySpec}
import play.api.libs.json.Json
import play.api.test.FakeRequest
import play.api.test.Helpers._


class UserImagesControllerTest extends PlaySpec with OneAppPerTest {
  val gson = new Gson()
  val userImages = UserImages(
    "SIT52",
    "458K",
    "DO67",
    "https://zi.com",
    "Triu",
    "GHJ",
    Option("gugu"),
    new DateTime("2004-12-13T21:39:45.618-08:00"))

  "Routes" should {
    "UserImagesController" should {

      "Create UserImages Object in Through Controller" in {
        val request = route(app, FakeRequest(POST, "/userImages/create")
          .withJsonBody(Json.toJson(userImages)))
          .get
        status(request) mustBe OK
        contentType(request) mustBe Some("application/json")
        println(" The Content is ", contentAsString(request))
      }

      "Get UserImages From Controller" in {
        val request = route(app, FakeRequest(GET, "/userImages/")
        ).get
        status(request) mustBe OK
        contentType(request) mustBe Some("application/json")
        println(" The Output", contentAsJson(request))
      }
    }
  }
} 
开发者ID:boniface,项目名称:hworkapi,代码行数:46,代码来源:UserImagesControllerTest.scala

示例15: UserPositionControllerTest

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

import com.google.gson.Gson
import domain.users.UserPosition
import org.joda.time.DateTime
import org.scalatestplus.play.{OneAppPerTest, PlaySpec}
import play.api.libs.json.Json
import play.api.test.FakeRequest
import play.api.test.Helpers._


class UserPositionControllerTest extends PlaySpec with OneAppPerTest {
  val gson = new Gson()
  val userImages = UserPosition(
    "SIT52",
    "458K",
    "DO67",
    new DateTime("2004-12-13T21:39:45.618-08:00"),
    "PO354",
    "Triu",
    "GHJ")

  "Routes" should {
    "UserPositionController" should {

      "Create UserPosition Object in Through Controller" in {
        val request = route(app, FakeRequest(POST, "/userPosition/create")
          .withJsonBody(Json.toJson(userImages)))
          .get
        status(request) mustBe OK
        contentType(request) mustBe Some("application/json")
        println(" The Content is ", contentAsString(request))
      }

      "Get UserPosition From Controller" in {
        val request = route(app, FakeRequest(GET, "/userPosition/")
        ).get
        status(request) mustBe OK
        contentType(request) mustBe Some("application/json")
        println(" The Output", contentAsJson(request))
      }
    }
  }
} 
开发者ID:boniface,项目名称:hworkapi,代码行数:45,代码来源:UserPositionControllerTest.scala


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