kotlinx-serialization / kotlinx.serialization.json / JsonInput

JsonInput

(common, js, jvm, native) interface JsonInput : Decoder, CompositeDecoder

Decoder used by Json during deserialization. This interface can be used to inject desired behaviour into a serialization process of Json.

Typical example of the usage:

// Class representing Either<Left|Right>
sealed class Either {
    data class Left(val errorMsg: String) : Either()
    data class Right(val data: Payload) : Either()
}

// Serializer injects custom behaviour by inspecting object content and writing
object EitherSerializer : KSerializer<Either> {
    override val descriptor: SerialDescriptor = SerialDescriptor("package.Either", PolymorphicKind.SEALED) {
         // ..
     }

    override fun deserialize(decoder: Decoder): Either {
        val input = decoder as? JsonInput ?: throw SerializationException("This class can be loaded only by Json")
        val tree = input.decodeJson() as? JsonObject ?: throw SerializationException("Expected JsonObject")
        if ("error" in tree) return Either.Left(tree.getPrimitive("error").content)
        return Either.Right(input.json.decodeJson(tree, Payload.serializer()))
    }

    override fun serialize(encoder: Encoder, value: Either) {
        val output = encoder as? JsonOutput ?: throw SerializationException("This class can be saved only by Json")
        val tree = when (value) {
          is Either.Left -> JsonObject(mapOf("error" to JsonLiteral(value.errorMsg)))
          is Either.Right -> output.json.toJson(value.data, Payload.serializer())
        }
        output.encodeJson(tree)
    }
}

Properties

(common, js, jvm, native)

json

An instance of the current Json.

abstract val json: Json

Functions

(common, js, jvm, native)

decodeJson

Decodes the next element in the current input as JsonElement. The type of the decoded element depends on the current state of the input and, when received by serializer in its KSerializer.serialize method, the type of the token directly matches the kind.

abstract fun decodeJson(): JsonElement