Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Make KotlinSerializer.kt more robust #524

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 the class is serialized as Any (i.e. 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))
}
}