JSON support using Gson
The GSON feature allows you to handle JSON content in your application easily usingthe 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 { 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 GsonBuilderused 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(..., ...)
}
}