Skip to content

Instantly share code, notes, and snippets.

@r4zzz4k
Created July 15, 2019 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save r4zzz4k/00c44feb3f2d8d44ad57e77852fe8db9 to your computer and use it in GitHub Desktop.
Save r4zzz4k/00c44feb3f2d8d44ad57e77852fe8db9 to your computer and use it in GitHub Desktop.
kotlinx.serlialization + Array<Any>
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