Last active
October 20, 2022 13:00
-
-
Save indrih17/ae48d69f41339faf92045cfc06d1aacc to your computer and use it in GitHub Desktop.
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
object AnySerializer : KSerializer<Any> { | |
override val descriptor: SerialDescriptor = buildClassSerialDescriptor("Any") | |
override fun serialize(encoder: Encoder, value: Any) { | |
val jsonEncoder = encoder as JsonEncoder | |
val jsonElement = serializeAny(value) | |
jsonEncoder.encodeJsonElement(jsonElement) | |
} | |
private fun serializeAny(value: Any?): JsonElement = when (value) { | |
is Map<*, *> -> { | |
val mapContents = value.entries.associate { mapEntry -> | |
mapEntry.key.toString() to serializeAny(mapEntry.value) | |
} | |
JsonObject(mapContents) | |
} | |
is List<*> -> { | |
val arrayContents = value.map { listEntry -> serializeAny(listEntry) } | |
JsonArray(arrayContents) | |
} | |
is Number -> JsonPrimitive(value) | |
is Boolean -> JsonPrimitive(value) | |
else -> JsonPrimitive(value.toString()) | |
} | |
override fun deserialize(decoder: Decoder): Any { | |
val jsonDecoder = decoder as JsonDecoder | |
val element = jsonDecoder.decodeJsonElement() | |
return deserializeJsonElement(element) | |
} | |
private fun deserializeJsonElement(element: JsonElement): Any = when (element) { | |
is JsonObject -> { | |
element.mapValues { deserializeJsonElement(it.value) } | |
} | |
is JsonArray -> { | |
element.map { deserializeJsonElement(it) } | |
} | |
is JsonPrimitive -> element.toString() | |
} | |
} |
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
open class EnumIntSerializer<E : Enum<E>>( | |
private val key: (E) -> Int, | |
private val enumCases: Array<E> | |
) : KSerializer<E> { | |
override val descriptor = PrimitiveSerialDescriptor("EnumIntSerializer", PrimitiveKind.INT) | |
override fun serialize(encoder: Encoder, value: E) { | |
encoder.encodeInt(key(value)) | |
} | |
override fun deserialize(decoder: Decoder): E { | |
val key = decoder.decodeInt() | |
return enumCases.first { key(it) == key } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment