Skip to content

Commit

Permalink
Update KotlinSerializer.kt
Browse files Browse the repository at this point in the history
Add handling of null, Void and Object
  • Loading branch information
geirsagberg authored Aug 1, 2024
1 parent d09ecbd commit 61df9e0
Showing 1 changed file with 12 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,23 @@ class KotlinSerializer : Serializer {
val CHARSET = StandardCharsets.UTF_8

override fun serialize(data: Any): ByteArray {
if (data == null) {
return ByteArray(0)
}
val serializer = serializer(data.javaClass)
return Json.encodeToString(serializer, data).toByteArray(CHARSET);
}

override fun <T : Any?> deserialize(clazz: Class<T>, serializedData: ByteArray): T {
if (serializedData == null || clazz == Void::class.java) {
return null
}

// If we do not know the class (e.g. java.lang.Object), decode as generic JSON
if (clazz == Any::class.java) {
return Json.decodeFromString(JsonElement.serializer(), serializedData.decodeToString()) as T
}

// Hackish workaround?
// https://github.com/Kotlin/kotlinx.serialization/issues/1134
// https://stackoverflow.com/questions/64284767/replace-jackson-with-kotlinx-serialization-in-javalin-framework/64285478#64285478
Expand Down

0 comments on commit 61df9e0

Please sign in to comment.