Skip to content

Instantly share code, notes, and snippets.

@deeprim
Last active June 26, 2019 22:15
Show Gist options
  • Save deeprim/68d5aeafb10e80a4ffb5aeed80e74e89 to your computer and use it in GitHub Desktop.
Save deeprim/68d5aeafb10e80a4ffb5aeed80e74e89 to your computer and use it in GitHub Desktop.
Kotlin Object Serializer
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)
}
@lzzy12
Copy link

lzzy12 commented Jan 2, 2019

Thanks :)

@TheLKL321
Copy link

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