toJsonElement

fun Any?.toJsonElement(json: Json? = null): JsonElement

Converts an arbitrary Kotlin value into a JsonElement — the inverse of toAny, and the general mechanism behind AnySerializable fields (an event's body, data, etc.) getting encoded onto the wire without the schema declaring a concrete type for them. Map/Iterable/Array/Pair/ Triple are converted structurally, primitives directly; anything else is only convertible when either json is supplied and its serializersModule has that type registered polymorphically, or the type itself has a @Serializable-generated serializer discoverable via serializerOrNull() — otherwise this throws, since there's no safe way to serialize an arbitrary object in Kotlin Multiplatform without one of those two.

Parameters

json

the Json instance whose serializersModule is checked for a polymorphic mapping, when the value's own generated serializer (if any) isn't enough — typically dev.catbit.mosaic.core.serialization.MosaicSerializer.json. Omit when only the value's own generated serializer should be tried.

Throws

SerializationException

if neither path can resolve a serializer for this value's runtime type.