Skip to content

Instantly share code, notes, and snippets.

@schmohlio
Created July 18, 2016 23:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save schmohlio/a0b5f0542a0cda96830b9333b56493f8 to your computer and use it in GitHub Desktop.
Save schmohlio/a0b5f0542a0cda96830b9333b56493f8 to your computer and use it in GitHub Desktop.
parse Json to Generic Java Map in Scala, similar to Jackson.
import com.google.gson.Gson
import java.util.{Map => JMap, LinkedHashMap}
type GenericDecoder = String => JMap[String, Object]
val decoder: GenericDecoder = {
// Gson instances are apparently thread-safe, so curry...
val gson: Gson = new Gson()
// LinkedHashMap preserves ordering. use HashMap if not required.
x => gson.fromJson(x, (new LinkedHashMap[String, Object]()).getClass)
}
val json = """
|{
| "hello": "world",
| "foods": ["macaroni", "broccoli", {"foo": "bar"}]
|}
|""".stripMargin
decode(json) // woohoo!
// validate roundtrip with Play Json
import play.api.libs.json._
Json.stringify(Json.parse(test)) == gson.toJson(decoder(test)) // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment