Data Conversion

DataConversion is a feature that allows to serialize and deserialize a list of values.

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.

Table of contents:

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

Basic Installation

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

  1. install(DataConversion)

Adding Converters

The DataConversion configuration, provide a convert<T> method to definetype conversions. Inside, you have to provide a decoder and an encoderwith the decode and encode methods accepting callbacks.

  • 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: samekey=item1&samekey=item2.

For example:

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

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. enum class LocationEnum {
  2. A, B, C
  3. }
  4. @Location("/") class LocationWithEnum(val e: LocationEnum)
  5. @Test fun `location class with custom enum value`() = withLocationsApplication {
  6. application.install(DataConversion) {
  7. convert(LocationEnum::class) {
  8. encode { if (it == null) emptyList() else listOf((it as LocationEnum).name.toLowerCase()) }
  9. decode { values, type -> LocationEnum.values().first { it.name.toLowerCase() in values } }
  10. }
  11. }
  12. application.routing {
  13. get<LocationWithEnum> {
  14. call.respondText(call.locations.resolve<LocationWithEnum>(LocationWithEnum::class, call).e.name)
  15. }
  16. }
  17. urlShouldBeHandled("/?e=a", "A")
  18. urlShouldBeHandled("/?e=b", "B")
  19. }

Accessing the Service

You can easily access the DataConversion service, from any call with:

  1. val dataConversion = call.conversionService

The ConversionService Interface

  1. interface ConversionService {
  2. fun fromValues(values: List<String>, type: Type): Any?
  3. fun toValues(value: Any?): List<String>
  4. }
  1. class DelegatingConversionService(private val klass: KClass<*>) : ConversionService {
  2. fun decode(converter: (values: List<String>, type: Type) -> Any?)
  3. fun encode(converter: (value: Any?) -> List<String>)
  4. }