Last active
June 15, 2018 15:30
-
-
Save ericharlow/ccd26b164fa69ca2fa1d4e94f25ebe99 to your computer and use it in GitHub Desktop.
Serializable to string and back
This file contains 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.* | |
/** | |
* 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