kotlinx-serialization / kotlinx.serialization.json / JsonLiteralSerializer / serialize

serialize

(common, js, jvm, native) fun serialize(encoder: Encoder, value: JsonLiteral): Unit

Serializes the value of type T using the format that is represented by the given encoder. serialize method is format-agnostic and operates with a high-level structured Encoder API. Throws SerializationException if value cannot be serialized.

Example of serialize method:

class MyData(int: Int, stringList: List<String>, alwaysZero: Long)

fun serialize(encoder: Encoder, value: MyData): Unit = encoder.encodeStructure(descriptor) {
    // encodeStructure encodes beginning and end of the structure
    // encode 'int' property as Int
    encodeIntElement(descriptor, index = 0, value.int)
    // encode 'stringList' property as List<String>
    encodeSerializableElement(descriptor, index = 1, serializer<List<String>>, value.stringList)
    // don't encode 'alwaysZero' property because we decided to do so
} // end of the structure