Created
July 15, 2019 13:11
-
-
Save r4zzz4k/00c44feb3f2d8d44ad57e77852fe8db9 to your computer and use it in GitHub Desktop.
kotlinx.serlialization + Array<Any>
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
package sample | |
import kotlinx.serialization.* | |
import kotlinx.serialization.internal.StringDescriptor | |
import kotlinx.serialization.json.* | |
object ToStringSerializer: KSerializer<Any> { | |
override val descriptor: SerialDescriptor = | |
StringDescriptor.withName("toString") | |
override fun serialize(encoder: Encoder, obj: Any) { | |
encoder.encodeString(obj.toString()) | |
} | |
override fun deserialize(decoder: Decoder): Any = error("This serializer doesn't support deserialization") | |
} | |
@Serializable | |
data class Message( | |
val action: String, | |
val method: String, | |
val args: Array<@Serializable(with = ToStringSerializer::class) Any>, | |
val id: String | |
) | |
@UseExperimental(UnstableDefault::class) | |
fun main() { | |
val json = Json | |
println(json.stringify( | |
Message.serializer(), | |
Message( | |
action = "Hello", | |
method = "world!", | |
args = arrayOf(1, "two", 3f), | |
id = "some id"))) | |
// output: {"action":"Hello","method":"world!","args":["1","two","3.0"],"id":"some id"} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment