JSON serialization plugin for Ktor HTTP client (JVM platform)
—
Google Gson-based JSON serialization implementation for Ktor HTTP clients. Provides high-performance JSON processing with configurable Gson builder support for custom serialization behavior.
JsonSerializer implementation using Google's Gson library for JSON processing.
/**
* JsonSerializer using Gson as backend.
*/
@Deprecated("Please use ContentNegotiation plugin and its converters")
class GsonSerializer(block: GsonBuilder.() -> Unit = {}) : JsonSerializer {
private val backend: Gson
/**
* Convert data object to OutgoingContent using Gson serialization.
*/
override fun write(data: Any, contentType: ContentType): OutgoingContent
/**
* Read content from response using Gson deserialization.
*/
override fun read(type: TypeInfo, body: Input): Any
}The GsonSerializer is automatically discoverable on JVM through the ServiceLoader mechanism:
META-INF/services/io.ktor.client.plugins.json.JsonSerializer
io.ktor.client.plugins.gson.GsonSerializerTo use GsonSerializer, add the Gson dependency to your project:
Gradle
implementation("io.ktor:ktor-client-gson:2.3.13")Maven
<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-client-gson-jvm</artifactId>
<version>2.3.13</version>
</dependency>import io.ktor.client.*
import io.ktor.client.plugins.json.*
import io.ktor.client.plugins.gson.*
val client = HttpClient {
install(JsonPlugin) {
serializer = GsonSerializer()
}
}val client = HttpClient {
install(JsonPlugin) {
serializer = GsonSerializer {
// Configure Gson builder
setPrettyPrinting()
setDateFormat("yyyy-MM-dd HH:mm:ss")
serializeNulls()
// Custom type adapters
registerTypeAdapter(LocalDateTime::class.java, LocalDateTimeAdapter())
// Field naming strategy
setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
// Exclusion strategy
setExclusionStrategies(object : ExclusionStrategy {
override fun shouldSkipField(f: FieldAttributes): Boolean {
return f.getAnnotation(Exclude::class.java) != null
}
override fun shouldSkipClass(clazz: Class<*>): Boolean = false
})
}
}
}data class User(
val id: Long,
val name: String,
val email: String,
@SerializedName("created_at")
val createdAt: String
)
// POST request - automatic serialization
val response = client.post("https://api.example.com/users") {
contentType(ContentType.Application.Json)
setBody(User(0, "Alice", "alice@example.com", "2023-01-01"))
}
// GET request - automatic deserialization
val user: User = client.get("https://api.example.com/users/1").body()// Custom type adapter for LocalDateTime
class LocalDateTimeAdapter : JsonSerializer<LocalDateTime>, JsonDeserializer<LocalDateTime> {
private val formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME
override fun serialize(
src: LocalDateTime,
typeOfSrc: Type,
context: JsonSerializationContext
): JsonElement {
return JsonPrimitive(src.format(formatter))
}
override fun deserialize(
json: JsonElement,
typeOfT: Type,
context: JsonDeserializationContext
): LocalDateTime {
return LocalDateTime.parse(json.asString, formatter)
}
}
// Usage with custom adapter
val client = HttpClient {
install(JsonPlugin) {
serializer = GsonSerializer {
registerTypeAdapter(LocalDateTime::class.java, LocalDateTimeAdapter())
}
}
}// Base class
abstract class Animal(val type: String)
// Implementations
data class Dog(val breed: String) : Animal("dog")
data class Cat(val color: String) : Animal("cat")
// Runtime type adapter
class AnimalTypeAdapter : RuntimeTypeAdapterFactory.of(Animal::class.java, "type")
.registerSubtype(Dog::class.java, "dog")
.registerSubtype(Cat::class.java, "cat")
val client = HttpClient {
install(JsonPlugin) {
serializer = GsonSerializer {
registerTypeAdapterFactory(AnimalTypeAdapter)
}
}
}// Serializing collections
val users = listOf(
User(1, "Alice", "alice@example.com", "2023-01-01"),
User(2, "Bob", "bob@example.com", "2023-01-02")
)
val response = client.post("https://api.example.com/users/batch") {
contentType(ContentType.Application.Json)
setBody(users)
}
// Deserializing collections
val userList: List<User> = response.body()try {
val user: User = client.get("https://api.example.com/users/1").body()
} catch (e: JsonSyntaxException) {
// Malformed JSON
logger.error("Invalid JSON response", e)
} catch (e: JsonIOException) {
// IO error during parsing
logger.error("IO error reading JSON", e)
}The GsonSerializer supports all standard Gson configuration options:
setPrettyPrinting()setDateFormat(pattern)serializeNulls()setFieldNamingPolicy(policy)registerTypeAdapter(type, adapter)setExclusionStrategies(strategy)setLenient()disableHtmlEscaping()@SerializedName for field mapping instead of global naming policiesInstall with Tessl CLI
npx tessl i tessl/maven-io-ktor--ktor-client-json-jvm