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 committed Aug 2, 2024
1 parent d09ecbd commit c8c6ac0
Showing 1 changed file with 22 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -1,25 +1,42 @@
package com.github.kagkarlsson.examples.kotlin

import com.github.kagkarlsson.scheduler.serializer.Serializer
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.serializer
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets

@OptIn(ExperimentalSerializationApi::class)
class KotlinSerializer : Serializer {
val CHARSET = StandardCharsets.UTF_8
private val charset: Charset = StandardCharsets.UTF_8

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

override fun <T : Any?> deserialize(clazz: Class<T>, serializedData: ByteArray): T {
@Suppress("UNCHECKED_CAST")
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

val deserializer = serializer(clazz) as KSerializer<T>
return Json.decodeFromString(deserializer, String(serializedData, CHARSET))
return Json.decodeFromString(deserializer, String(serializedData, charset))
}
}

0 comments on commit c8c6ac0

Please sign in to comment.