Skip to content

Instantly share code, notes, and snippets.

@ericharlow
Last active June 15, 2018 15:30
Show Gist options
  • Save ericharlow/ccd26b164fa69ca2fa1d4e94f25ebe99 to your computer and use it in GitHub Desktop.
Save ericharlow/ccd26b164fa69ca2fa1d4e94f25ebe99 to your computer and use it in GitHub Desktop.
Serializable to string and back
import java.io.*
/**
* Returns an empty string if something goes wrong internally
*/
fun serializableToString(item : Serializable) : String {
var result = ""
try {
val stream = ByteArrayOutputStream()
val objectStream = ObjectOutputStream(stream)
objectStream.writeObject(item)
objectStream.close()
result = stream.toString()
stream.close()
} catch (t : Throwable) {
// nothing to do
}
return result
}
/**
* Returns null if something goes wrong internally
*/
fun stringToSerializable(stringValue: String): Serializable? {
var serializable: Serializable? = null
try {
val stream = ByteArrayInputStream(stringValue.toByteArray())
val objectStream = ObjectInputStream(stream)
serializable = objectStream.readObject() as Serializable
objectStream.close()
stream.close()
} catch (t : Throwable) {
// nothing to do
}
return serializable
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment