Created
July 18, 2016 23:34
-
-
Save schmohlio/a0b5f0542a0cda96830b9333b56493f8 to your computer and use it in GitHub Desktop.
parse Json to Generic Java Map in Scala, similar to Jackson.
This file contains hidden or 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 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