JSON support using Gson

Estimated reading time: 1 minute

The GSON feature allows you to handle JSON content in your application easily using the google-gson library.

This feature is a ContentNegotiation converter.

This feature is defined in the class io.ktor.gson.GsonConverter in the artifact io.ktor:ktor-gson:$ktor_version.
dependencies { compile "io.ktor:ktor-gson:$ktor_version" }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-gson</artifactId> <version>${ktor.version}</version> </dependency> </dependencies> </project>

Basic usage

Install the feature by registering a JSON content converter using Gson:

install(ContentNegotiation) {
    gson {
        // Configure Gson here
    }
}

The gson block is a convenient method for:

register(ContentType.Application.Json, GsonConverter(GsonBuilder().apply {
    // ...
}.create()))

Configuration

Inside the gson block, you have access to the GsonBuilder used to install the ContentNegotiation. To give you an idea of what is available:

install(ContentNegotiation) {
    gson {
        setPrettyPrinting()
        
        disableHtmlEscaping()
        disableInnerClassSerialization()
        enableComplexMapKeySerialization()

        serializeNulls()

        serializeSpecialFloatingPointValues()
        excludeFieldsWithoutExposeAnnotation()
        
        setDateFormat(...)

        generateNonExecutableJson()

        setFieldNamingPolicy()
        setLenient()
        setLongSerializationPolicy(...)
        setExclusionStrategies(...)
        setVersion(0.0)
        addDeserializationExclusionStrategy(...)
        addSerializationExclusionStrategy(...)
        excludeFieldsWithModifiers(Modifier.TRANSIENT)
        
        registerTypeAdapter(...)
        registerTypeAdapterFactory(...)
        registerTypeHierarchyAdapter(..., ...)
    }
}