Skip to content

Instantly share code, notes, and snippets.

@laughedelic
Created September 7, 2017 02:27
Show Gist options
  • Save laughedelic/634f1a1e5333d58085603fcff317f6b4 to your computer and use it in GitHub Desktop.
Save laughedelic/634f1a1e5333d58085603fcff317f6b4 to your computer and use it in GitHub Desktop.
Shows how to serialize-deserialize an object in Scala to a String
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)))
@laughedelic
Copy link
Author

Based on this SO answer, but with bytes Base64 encoding/decoding, which appears to be important, if you serialize to String and back.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment