Created
September 7, 2017 02:27
-
-
Save laughedelic/634f1a1e5333d58085603fcff317f6b4 to your computer and use it in GitHub Desktop.
Shows how to serialize-deserialize an object in Scala to a String
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 java.io._ | |
import java.util.Base64 | |
import java.nio.charset.StandardCharsets.UTF_8 | |
def serialise(value: Any): String = { | |
val stream: ByteArrayOutputStream = new ByteArrayOutputStream() | |
val oos = new ObjectOutputStream(stream) | |
oos.writeObject(value) | |
oos.close | |
new String( | |
Base64.getEncoder().encode(stream.toByteArray), | |
UTF_8 | |
) | |
} | |
def deserialise(str: String): Any = { | |
val bytes = Base64.getDecoder().decode(str.getBytes(UTF_8)) | |
val ois = new ObjectInputStream(new ByteArrayInputStream(bytes)) | |
val value = ois.readObject | |
ois.close | |
value | |
} | |
println(deserialise(serialise("My Test"))) | |
println(deserialise(serialise(List(1)))) | |
println(deserialise(serialise(Map(1 -> 2)))) | |
println(deserialise(serialise(1))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on this SO answer, but with bytes Base64 encoding/decoding, which appears to be important, if you serialize to
String
and back.