All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.com.bselzer.ktx.serialization.context.XmlContext.kt Maven / Gradle / Ivy

There is a newer version: 6.5.0
Show newest version
package com.bselzer.ktx.serialization.context

import kotlinx.serialization.DeserializationStrategy
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import nl.adaptivity.xmlutil.serialization.XML
import nl.adaptivity.xmlutil.serialization.XmlValue

open class XmlContext(
    override val instance: XML
) : StringFormatContext(instance) {
    companion object Default : XmlContext(XML.defaultInstance)

    internal class Wrapper(
        @XmlValue
        val value: T
    )

    internal class WrapperSerializer(
        private val valueSerializer: DeserializationStrategy
    ) : DeserializationStrategy> {
        @OptIn(ExperimentalSerializationApi::class)
        override val descriptor: SerialDescriptor = SerialDescriptor("Wrapper", valueSerializer.descriptor)

        override fun deserialize(decoder: Decoder): Wrapper {
            val value = decoder.decodeSerializableValue(valueSerializer)
            return Wrapper(value)
        }
    }

    override fun  String.decode(deserializer: DeserializationStrategy): T {
        val wrapper = WrapperSerializer(deserializer)
        return instance.decodeFromString(wrapper, "$this").value
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy