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>
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()))
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(..., ...)
}
}