-
-
Notifications
You must be signed in to change notification settings - Fork 191
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Showing
1 changed file
with
22 additions
and
5 deletions.
There are no files selected for viewing
27 changes: 22 additions & 5 deletions
27
examples/features/src/main/java/com/github/kagkarlsson/examples/kotlin/KotlinSerializer.kt
This file contains 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
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)) | ||
} | ||
} |