Last active
August 29, 2015 14:22
-
-
Save adamv/28f275ca7ca87818ef53 to your computer and use it in GitHub Desktop.
JSON string -> ? -> Smile
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.fasterxml.jackson.core.JsonFactory | |
| import com.fasterxml.jackson.databind.ObjectMapper | |
| import com.fasterxml.jackson.databind.util.TokenBuffer | |
| import com.fasterxml.jackson.dataformat.smile.SmileFactory | |
| object SmileDemo { | |
| val JSON_FACTORY: JsonFactory = new JsonFactory() | |
| val SMILE_FACTORY: SmileFactory = new SmileFactory() | |
| val JSON = new ObjectMapper(JSON_FACTORY) | |
| val SMILE = new ObjectMapper(SMILE_FACTORY) | |
| def stringToSmileThroughTree(s: String): Array[Byte] = { | |
| SMILE.writeValueAsBytes(JSON.readTree(s)) | |
| } | |
| def stringToSmileThroughBuffer(s: String): Array[Byte] = { | |
| val p = JSON_FACTORY.createParser(s) | |
| SMILE.writeValueAsBytes(p.readValueAs(classOf[TokenBuffer])) | |
| } | |
| def main(args: Array[String]): Unit = { | |
| convert(stringToSmileThroughTree) | |
| println() | |
| convert(stringToSmileThroughBuffer) | |
| } | |
| def convert(fun: (String) => Array[Byte]): Unit = { | |
| val someData = """{"abc": "def", "ghi": 129, "jkl": null}""" | |
| val bytes = fun(someData) | |
| println(bytes.length + " bytes") | |
| var i: Integer = 0 | |
| for (b <- bytes) { | |
| print("%02X".format(b)) | |
| i += 1 | |
| print(if (i % 16 == 0) "\n" else " ") | |
| } | |
| println() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment