CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-io-ktor--ktor-client-json-jvm

JSON serialization plugin for Ktor HTTP client (JVM platform)

Pending
Overview
Eval results
Files

gson-serializer.mddocs/

Gson Serialization

Google Gson-based JSON serialization implementation for Ktor HTTP clients. Provides high-performance JSON processing with configurable Gson builder support for custom serialization behavior.

Capabilities

GsonSerializer Class

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
}

Service Registration

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.GsonSerializer

Dependencies

To 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>

Usage Examples

Basic Usage

import io.ktor.client.*
import io.ktor.client.plugins.json.*
import io.ktor.client.plugins.gson.*

val client = HttpClient {
    install(JsonPlugin) {
        serializer = GsonSerializer()
    }
}

Custom Gson Configuration

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 Classes with Gson

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()

Complex Type Handling

// 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())
        }
    }
}

Polymorphic Serialization

// 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)
        }
    }
}

Collection Handling

// 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()

Error Handling

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)
}

Gson Configuration Options

The GsonSerializer supports all standard Gson configuration options:

  • Pretty Printing: setPrettyPrinting()
  • Date Formatting: setDateFormat(pattern)
  • Null Serialization: serializeNulls()
  • Field Naming: setFieldNamingPolicy(policy)
  • Type Adapters: registerTypeAdapter(type, adapter)
  • Exclusion Strategies: setExclusionStrategies(strategy)
  • Lenient Parsing: setLenient()
  • HTML Escaping: disableHtmlEscaping()

Performance Considerations

  • Gson instances are thread-safe and should be reused
  • Type adapters are cached internally for better performance
  • Consider using @SerializedName for field mapping instead of global naming policies
  • Use exclusion strategies judiciously as they impact performance

Install with Tessl CLI

npx tessl i tessl/maven-io-ktor--ktor-client-json-jvm

docs

gson-serializer.md

index.md

jackson-serializer.md

json-plugin.md

json-serializer.md

kotlinx-serializer.md

tile.json