Skip to content

Serialisation

KForm itself provides no framework for serialisation. It does, however, in typical Kotlin Multiplatform fashion, provide serialisers for kotlinx.serialization.

All serialisers are provided in the tech.ostack.kform.serializers package.

The previously introduced model of a form for purchasing bus tickets can be made serialisable by annotating all model classes with @Serializable:

Serialisable model of a form for purchasing bus tickets
@JsExport
@Serializable
data class BusTripForm(
    var email: String = "",
    var passengers: Table<Passenger> = tableOf(),
)

@JsExport @Serializable data class Passenger(var name: String = "", var age: Int? = null)

To, for example, serialise the form to JSON, the following utilities can be used together with kotlinx-serialization-json:

Utilities for serialising a form as JSON
private val JSON_CONFIG = Json.Default
private val JSON_CONFIG_PRETTY = Json(JSON_CONFIG) { prettyPrint = true }

fun jsonConfig(prettyPrint: Boolean = false): Json =
    if (prettyPrint) JSON_CONFIG_PRETTY else JSON_CONFIG

@JsExport
fun encodeBusTripFormToString(form: BusTripForm, prettyPrint: Boolean = false): String =
    jsonConfig(prettyPrint).encodeToString(form)

@JsExport
fun decodeBusTripFormFromString(json: String): BusTripForm = jsonConfig().decodeFromString(json)

Paths

Both path classes have a default kotlin.serialization serialiser:

Validation issues

Both localised and non-localised validation issues have a default kotlin.serialization serialiser:

Tables

Tables can be serialised via one of two serialisers:

  • TableSerializer: serialises the table rows as a map of identifiers to their values. This is the default serialiser.
  • TableValuesSerializer: serialises the table rows as a list of values, ignoring all row identifiers. Example usage:

    @JsExport
    @Serializable
    data class BusTripForm(
        var email: String = "",
        @Serializable(with = TableValuesSerializer::class)
        var passengers: Table<Passenger> = tableOf(),
    )
    

Files

Files can be serialised via one of two serialisers:

  • FileSerializer: serialises the file’s data as a byte array. This is the default serialiser.
  • FileBase64Serializer: serialises the file’s data as a base 64 string. Useful when using formats such as JSON which do not support binary data. Example usage:

    @JsExport
    @Serializable
    data class Passenger(
        var name: String = "",
        var age: Int? = null,
        @Serializable(with = FileBase64Serializer::class) var idDocument: File? = null,
    )
    

Big integers & decimals

The kt-math library does not provide kotlinx.serialization serialisers for BigInteger and BigDecimal.

KForm provides typealiases for both classes, with serialisers already applied:

Make sure to import BigInteger and BigDecimal from the tech.ostack.kform.datatypes package instead of org.gciatto.kt.math when defining your serialisable form model.