Skip to content

Instantly share code, notes, and snippets.

@darekmydlarz
Created September 5, 2012 17:48
Show Gist options
  • Save darekmydlarz/3641114 to your computer and use it in GitHub Desktop.
Save darekmydlarz/3641114 to your computer and use it in GitHub Desktop.
Scala + Gson
// lib to add: http://code.google.com/p/google-gson/downloads/detail?name=google-gson-2.2.2-release.zip&can=2&q=
// file Main.scala
package demo
import scala.collection.JavaConverters._
import com.google.gson.Gson
import java.util.ArrayList
import java.lang.reflect.Type
import com.google.gson.reflect.TypeToken
object Main {
def main(args : Array[String]) {
val gson : Gson = new Gson()
val list : ArrayList[String] = new ArrayList[String]
list.add("Dario")
list.add("Dario2")
val tmp : MyType = new MyType("A", list)
println("Object :" + tmp)
val json : String = gson.toJson(tmp)
println("Object2json: " + json)
val jsonString = "[{\"x\":\"A\",\"y\":[\"Dario\",\"Dario2\"]}, {\"x\":\"A\",\"y\":[\"Dario\",\"Dario2\"]}]";
// listType konieczny do odpowiedniego przekonwertowania Jsona przez biblioteke Gson
val listType : Type = new TypeToken[ArrayList[MyType]]() {}.getType()
val tmp2 : ArrayList[MyType] = (gson.fromJson(jsonString, listType))
println("Json2object: " + tmp2)
}
}
// file MyType.scala
package demo
import scala.collection.JavaConverters._
import com.google.gson.Gson
import java.util.ArrayList
case class MyType (val x:String, val y:ArrayList[String]) {
def toJson() = new Gson().toJson(this)
override def toString() : String = {
x + ", " + y
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment