JSON support using Gson

预计阅读时间: 2 分钟

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

This feature is a ContentNegotiation converter.

本特性在构件 io.ktor:ktor-gson:$ktor_version 中的 io.ktor.gson.GsonConverter 类中定义
dependencies { implementation "io.ktor:ktor-gson:$ktor_version" }
dependencies { implementation("io.ktor:ktor-gson:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-gson</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </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(..., ...)
    }
}