gson機能を使うと、JSONコンテンツをあなたのアプリケーション内でgoogle-gsonライブラリを使って簡単に扱うことができるようになります。
この機能はContentNegotiationコンバーターです。
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>
Gsonを使ったJSONコンテンツコンバーターを登録することでこの機能をインストールします:
install(ContentNegotiation) {
gson {
// Configure Gson here
}
}
gson
ブロックは以下の意味を持つ便利なメソッドです:
register(ContentType.Application.Json, GsonConverter(GsonBuilder().apply {
// ...
}.create()))
gson
ブロック内で、ContentNegotiationをインストールするために使われたGsonBuilderにアクセスできます。
以下を、何ができるのかの参考にしてください:
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(..., ...)
}
}