Last active
September 3, 2015 15:59
-
-
Save mlimotte/23927d111aadfa13d38f to your computer and use it in GitHub Desktop.
Scala code for conversion of arbitrary nested data structures (list, maps, sets, values) to a JSON string. This involves converting the nested Scala collections (mutable/immutable Maps, Sets, Iterables, etc) to their Java counterparts., which is done with a a distinct function in the gist (toJava).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.gson.Gson | |
import scala.collection.JavaConversions | |
val gson = new Gson() | |
val mapPrototype = new java.util.HashMap[String,Any]() | |
def parseJson(json: String): Map[String,Any] = { | |
// Note: mapAsScalaMap is a wrapper, the data is NOT copied | |
scala.collection.JavaConversions.mapAsScalaMap(gson.fromJson(json, mapPrototype.getClass)).toMap | |
} | |
val sampleJson="{\"k1\":\"v1\",\"k2\":10, \"k3\":[1,2,3]}" | |
def toJava(x: Any): Any = { | |
import scala.collection.JavaConverters._ | |
x match { | |
case y: scala.collection.MapLike[_, _, _] => | |
y.map { case (d, v) => toJava(d) -> toJava(v) } asJava | |
case y: scala.collection.SetLike[_,_] => | |
y map { item: Any => toJava(item) } asJava | |
case y: Iterable[_] => | |
y.map { item: Any => toJava(item) } asJava | |
case y: Iterator[_] => | |
toJava(y.toIterable) | |
case _ => | |
x | |
} | |
} | |
def scalaToJson(x: Any): String = { | |
gson.toJson(toJava(x)) | |
} | |
val result = parseJson(sampleJson) | |
println(result.get("k3").get) | |
println(result.get("doesnt exist")) | |
val r2 = result + ("baz"-> Seq(Seq("a", "b"), scala.collection.mutable.Map("abc"->1.0))) + ("quux"->Seq(Map("x"->1))) + ("zet"->Set(1,2,Seq(3,4))) | |
scalaToJson(r2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment