Computer scienceBackendSpring BootWeb

kotlinx.serialization in Spring Boot

When a Spring Boot application receives a request body or sends a response body, something has to convert between Kotlin objects and a format such as JSON. The controller doesn't do this itself. Spring does it with HTTP message converters, which pick up the body, find a library that can handle the type, and read or write it. In Spring Boot, that library has traditionally been Jackson.

Spring Boot 4 (built on Spring Framework 7) adds first-party support for kotlinx.serialization. Spring Boot configures the library for you, and Spring picks it for your @Serializable classes while Jackson keeps working for everything else.

In this topic, you'll learn how to add the support, how to configure it with properties, and how it coexists with Jackson. The topic assumes that you know the basics of kotlinx.serialization: @Serializable classes and the Json configuration. If you need a refresh, see the Kotlin serialization overview and the guide to JSON features.

The Spring Boot starter

To use kotlinx.serialization with Spring Boot, you need the serialization compiler plugin, which generates the serializers for your classes, and the Spring Boot starter:

// build.gradle.kts
plugins {
    kotlin("plugin.serialization") version "<your Kotlin version>"
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-webmvc")
    implementation("org.springframework.boot:spring-boot-starter-kotlinx-serialization-json")
}

The starter is available since Spring Boot 4.0 (under this name since 4.0.1). Adding only the kotlinx-serialization-json library to your project is not enough for Spring Boot to configure anything. The starter brings that library together with Spring Boot's auto-configuration for it. With the starter on the classpath, Spring Boot:

  • creates a Json bean, configured from the spring.kotlinx.serialization.json.* properties;

  • registers a message converter, KotlinSerializationJsonHttpMessageConverter, that uses this Json bean.

After that, you use @Serializable classes in a controller as usual, and no other configuration is needed:

@Serializable
data class BookRequest(val title: String, val pageCount: Int = 100)

@Serializable
data class BookResponse(val id: Long, val title: String, val pageCount: Int, val subtitle: String? = null)

@RestController
@RequestMapping("/api/books")
class BookController {

    @PostMapping
    fun create(@RequestBody request: BookRequest): BookResponse =
        BookResponse(id = 1, title = request.title, pageCount = request.pageCount)
}

A matching spring-boot-starter-kotlinx-serialization-json-test starter exists for your tests.

Coexisting with Jackson

You don't have to remove Jackson from your project, and in practice you rarely can. spring-boot-starter-webmvc includes Jackson, and other parts of Spring Boot that produce JSON on their own, such as actuator endpoints and the default error responses, are built on it. So having both libraries on the classpath is the normal setup.

Spring Boot and Spring Framework 7 are designed for this setup:

  • When both the starter and Jackson are present, Spring Boot registers KotlinSerializationJsonHttpMessageConverter ahead of the Jackson converter. You don't need to write a WebMvcConfigurer or change the order of converters yourself.

  • In this case, the kotlinx converter only matches types that are annotated with @Serializable, and collections and maps of such types. This is a deliberate restriction: kotlinx.serialization is made for @Serializable classes, and without the restriction it would also grab types that Jackson should handle.

The result is a clean split. A message converter is chosen per type, and the first one that matches wins:

  • A class marked @Serializable, like BookResponse, is handled by kotlinx.serialization.

  • Any class without @Serializable, such as types from other libraries or the infrastructure of Spring Boot, falls through to Jackson.

Two things follow from this split. First, the two libraries are configured separately: spring.kotlinx.serialization.json.* affects only the types handled by kotlinx.serialization, and spring.jackson.* only the types handled by Jackson. A setting of one doesn't change the output of the other. Second, if you're not sure which library handled a type, check the JSON that it produces, especially for unusual shapes such as nested generic types. Types that the @Serializable check doesn't recognize are handled by Jackson.

If Jackson isn't on the classpath at all, the @Serializable restriction is not applied, and the kotlinx converter can also handle types without the annotation, such as String, numbers, and lists of them.

Configuring the Json bean with properties

You configure the Json instance with properties in application.properties:

spring.kotlinx.serialization.json.ignore-unknown-keys=true
spring.kotlinx.serialization.json.encode-defaults=true
spring.kotlinx.serialization.json.explicit-nulls=false
spring.kotlinx.serialization.json.naming-strategy=snake_case
spring.kotlinx.serialization.json.pretty-print=false

The same keys work in application.yml. Each property corresponds to a setting that you know from the Json { ... } builder. Some of those settings are marked as experimental in kotlinx.serialization, and setting them through properties means that your code doesn't need @OptIn. The full list of properties is in the Spring Boot reference, in the common application properties.

These settings have the biggest effect on what your API accepts and returns:

  • ignore-unknown-keys. By default, a request that contains a property that your class doesn't have is rejected. Set this to true if clients may send extra fields.

  • encode-defaults. By default, a property whose value equals its default is not written. Set it to true to always write defaults.

  • explicit-nulls. By default, a nullable property that is null is written as null. Set it to false to leave such properties out. It also affects reading: a nullable property that is missing from the request becomes null.

  • naming-strategy. Converts property names, for example from pageCount to page_count with snake_case. It applies both to the JSON that you write and to the JSON that you read.

  • pretty-print. Formats the output with indentation, which is mostly useful for debugging.

These settings combine. Here is the JSON for BookResponse(id = 1, title = "Kotlin", pageCount = 300), where subtitle is null:

Settings

JSON

defaults

{"id":1,"title":"Kotlin","pageCount":300}

encode-defaults=true

{"id":1,"title":"Kotlin","pageCount":300,"subtitle":null}

encode-defaults=true, explicit-nulls=false

{"id":1,"title":"Kotlin","pageCount":300}

naming-strategy=snake_case

{"id":1,"title":"Kotlin","page_count":300}

With the defaults, subtitle is omitted because it equals its default value. With encode-defaults=true, the default value is written, as null. Adding explicit-nulls=false removes it again.

When reading a request, a property that has no default value and is missing from the JSON causes an error. In BookRequest, title is required, but pageCount is optional because it has a default. A body that doesn't match your class is rejected before your controller method runs, so you handle those failures the same way as other request errors.

For settings that have no property, such as a custom serializers module, define a KotlinxSerializationJsonBuilderCustomizer bean. It receives the JsonBuilder that Spring Boot uses to create the Json bean:

@Bean
fun jsonCustomizer() = KotlinxSerializationJsonBuilderCustomizer { builder ->
    builder.classDiscriminator = "kind"
}

Prefer properties for what they cover, and use a customizer only for the rest.

Conclusion

Spring Boot 4 and Spring Framework 7 support kotlinx.serialization out of the box. You add the serialization compiler plugin and spring-boot-starter-kotlinx-serialization-json, which brings the library and Spring Boot's auto-configuration. The auto-configuration creates a Json bean from the spring.kotlinx.serialization.json.* properties and registers a message converter that uses it.

Jackson stays on the classpath, and the two libraries share the work. Spring Boot puts the kotlinx converter ahead of Jackson's, and it only matches @Serializable types, so your annotated classes go through kotlinx.serialization and everything else falls through to Jackson. Each library has its own configuration. The properties ignore-unknown-keys, encode-defaults, explicit-nulls, and naming-strategy decide what your API accepts and returns, so choose them deliberately and test the output.

How did you like the theory?
Report a typo