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?
Acceptsvalues
, a list of strings) representing repeated values in the URL, for example,a=1&a=2
,and accepts thetype
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 askey=item1
. For multiple values,it will be serialized in the query string as: .
For example:
convert<Date> { // this: DelegatingConversionService
val format = SimpleDateFormat.getInstance()
decode { values, _ -> // converter: (values: List<String>, type: Type) -> Any?
values.singleOrNull()?.let { format.parse(it) }
}
encode { value -> // converter: (value: Any?) -> List<String>
when (value) {
else -> throw DataConversionException("Cannot convert $value as Date")
}
}
}
}
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:
val dataConversion = call.conversionService
class DelegatingConversionService(private val klass: KClass<*>) : ConversionService {
fun decode(converter: (values: List<String>, type: Type) -> Any?)
}