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:

  1. install(ContentNegotiation) {
  2. gson {
  3. // Configure Gson here
  4. }
  5. }

The gson block is a convenient method for:

  1. register(ContentType.Application.Json, GsonConverter(GsonBuilder().apply {
  2. // ...
  3. }.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:

  1. install(ContentNegotiation) {
  2. gson {
  3. setPrettyPrinting()
  4. disableHtmlEscaping()
  5. disableInnerClassSerialization()
  6. enableComplexMapKeySerialization()
  7. serializeNulls()
  8. serializeSpecialFloatingPointValues()
  9. excludeFieldsWithoutExposeAnnotation()
  10. setDateFormat(...)
  11. generateNonExecutableJson()
  12. setFieldNamingPolicy()
  13. setLenient()
  14. setLongSerializationPolicy(...)
  15. setExclusionStrategies(...)
  16. setVersion(0.0)
  17. addDeserializationExclusionStrategy(...)
  18. addSerializationExclusionStrategy(...)
  19. excludeFieldsWithModifiers(Modifier.TRANSIENT)
  20. registerTypeAdapter(...)
  21. registerTypeAdapterFactory(...)
  22. registerTypeHierarchyAdapter(..., ...)
  23. }
  24. }