Data Conversion

    By default, it handles primitive types and enums, but it can also be configured to handle additional types.

    If you are using the Locations feature and want to supportcustom types as part of its parameters, you can add new custom converters with thisservice.

    This feature is defined in the class io.ktor.features.DataConversion and no additional artifacts are required.

    Installing the DataConversion is pretty easy, and it should be cover primitive types:

    • decode callback: converter: (values: List<String>, type: Type) -> Any?Accepts values, a list of strings) representing repeated values in the URL, for example, a=1&a=2,and accepts the type to convert to. It should return the decoded value.
    • encode callback: converter: (value: Any?) -> List<String> Accepts an arbitrary value, and should return a list of strings representing the value.When returning a list of a single element, it will be serialized as key=item1. For multiple values,it will be serialized in the query string as: .

    For example:

    1. convert<Date> { // this: DelegatingConversionService
    2. val format = SimpleDateFormat.getInstance()
    3. decode { values, _ -> // converter: (values: List<String>, type: Type) -> Any?
    4. values.singleOrNull()?.let { format.parse(it) }
    5. }
    6. encode { value -> // converter: (value: Any?) -> List<String>
    7. when (value) {
    8. else -> throw DataConversionException("Cannot convert $value as Date")
    9. }
    10. }
    11. }
    12. }

    Another potential use is to customize how a specific enum is serialized. By default enums are serialized and de-serializedusing its .name in a case-sensitive fashion. But you can for example serialize them as lower case and deserializethem in a case-insensitive fashion:

    1. val dataConversion = call.conversionService
    1. class DelegatingConversionService(private val klass: KClass<*>) : ConversionService {
    2. fun decode(converter: (values: List<String>, type: Type) -> Any?)
    3. }