Last active
June 26, 2019 22:15
-
-
Save deeprim/68d5aeafb10e80a4ffb5aeed80e74e89 to your computer and use it in GitHub Desktop.
Kotlin Object Serializer
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.* | |
object ObjectSerializer { | |
/** | |
* Serialize given object into [String] using [ObjectOutputStream]. | |
* @param obj object to serialize | |
* @see ObjectInputStream | |
* @return the serialization result, empty string for _null_ input | |
*/ | |
fun <T : Serializable> serialize(obj: T?): String { | |
if (obj == null) { | |
return "" | |
} | |
val baos = ByteArrayOutputStream() | |
val oos = ObjectOutputStream(baos) | |
oos.writeObject(obj) | |
oos.close() | |
return baos.toString("ISO-8859-1") | |
} | |
/** | |
* Deserialize given [String] using [ObjectInputStream]. | |
* @param string the string to deserialize | |
* @return deserialized object, null, in case of error. | |
*/ | |
fun <T : Serializable> deserialize(string: String): T? { | |
if (string.isEmpty()) { | |
return null | |
} | |
var bais = ByteArrayInputStream(string.toByteArray(charset("ISO-8859-1"))) | |
var ois = ObjectInputStream(bais) | |
return ois.readObject() as T | |
} | |
fun <T : Serializable> deserialize(string: String, clazz: Class<T>): T? = deserialize<T>(string) | |
} |
Used a slightly modified version, thank you :D
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks :)