Gson — what is it, JSON library for Java and Kotlin

Author: IT Sectr Published: 2026-03-15 Reading time: 8 min

Gson — a library from Google for serializing Java objects to JSON and back, widely used in Android development. It allows converting complex object graphs into compact JSON strings without writing parsers manually. According to Google Gson, 2024, the library has over 23 thousand stars on GitHub and remains one of the most popular solutions for working with JSON in the Java and Kotlin ecosystem.

Key Takeaways

  • Gson — Google library for JSON serialization in Java and Kotlin
  • fromJson — deserializes JSON into any Java object type
  • toJson — serializes an object into a JSON string
  • @SerializedName — annotation for mapping a JSON key to a class field
  • TypeToken — working with generics and parameterized types

What is Gson

Gson is a Java library developed by Google for converting objects to JSON representation and back. It uses reflection to analyze class structures, allowing it to work without prior configuration. Gson supports arbitrary Java objects, collections, arrays, generics, and nested classes. The library does not require annotations for basic use but provides them for fine-tuning. The main drawback of reflection is reduced performance during initialization and inability to optimize at compile time, which is especially noticeable on cold start of an Android application when deserializing hundreds of models. Despite this, Gson remains a reliable choice for most projects thanks to its stability and extensive documentation.

History and place in the ecosystem

Gson was released by Google in 2008 and quickly became the de facto standard for JSON in Android applications. Before the advent of Moshi and kotlinx.serialization, Gson was the only popular choice for Kotlin projects. Ease of integration — adding a single dependency to build.gradle — and the absence of mandatory annotations made Gson popular among developers of all skill levels.

groovy
// Adding Gson in build.gradle
dependencies {
    implementation 'com.google.code.gson:gson:2.10.1'
}

// Basic usage
data class User(
    val id: Int,
    val name: String,
    val email: String
)

val gson = Gson()
val user = User(1, "John", "john@test.com")
val json = gson.toJson(user)
println(json) // {"id":1,"name":"John","email":"john@test.com"}

In addition to basic serialization, Gson provides GsonBuilder for configuring behavior: date formatting, disabling HTML escaping, key case formatting, and custom instances. GsonBuilder also allows registering custom JsonSerializer and JsonDeserializer for types that the library cannot handle automatically. Configuration flexibility makes GsonBuilder an indispensable and useful tool when adapting the library to specific project requirements in modern Android development.

Main operations toJson and fromJson

toJson converts a Java object into a JSON string by analyzing its fields through reflection. By default, Gson includes all fields except transient and static ones. The method supports any types: primitives, objects, collections, and arrays. fromJson performs the reverse operation, accepting a JSON string and the target object class, and returns an instance with populated fields.

Converting an object to JSON

During serialization, Gson recursively traverses all object fields, including nested ones. Cyclic references lead to StackOverflowError, so they must be excluded using the @Expose annotation or a custom adapter. For collections, Gson preserves element types, but when deserializing a list with generics, TypeToken is required to preserve type information.

kotlin
// data class with nested object
data class Address(
    val city: String,
    val street: String
)

data class Employee(
    val id: Int,
    val name: String,
    val address: Address
)

val gson = Gson()
val employee = Employee(1, "Alice",
    Address("New York", "5th Ave"))

// Serialization to JSON
val json = gson.toJson(employee)

// Deserialization from JSON
val jsonString = """
{"id":2,"name":"Bob","address":{"city":"London","street":"Baker St"}}
"""
val parsed = gson.fromJson(jsonString, Employee::class.java)

Annotations and configuration

Gson provides a set of annotations for managing the serialization process. @SerializedName specifies the JSON key name that differs from the field name. @Expose controls whether a field is included in serialization: Gson created via GsonBuilder.excludeFieldsWithoutExposeAnnotation() will only process fields with @Expose. @Since and @Until control field versioning.

@SerializedName and @Expose

The @SerializedName annotation solves the problem of name mismatch: the server may use snake_case while the code uses camelCase. The annotation accepts a value and optional alternatives for backward compatibility. @Expose allows hiding sensitive fields (passwords, tokens) from serialization by marking them as @Expose(serialize = false). In addition to inclusion and exclusion, @Expose can be combined with GsonBuilder.excludeFieldsWithoutExposeAnnotation to create a whitelist of fields, which helps control the attack surface when serializing objects with many fields.

kotlin
// Model with Gson annotations
data class UserResponse(
    @SerializedName("user_id")
    val userId: Int,

    @SerializedName("full_name",
        alternate = [Alternative("name")])
    val fullName: String,

    @Expose(serialize = false)
    val password: String
)

// Gson with @Expose filtering
val gson = GsonBuilder()
    .excludeFieldsWithoutExposeAnnotation()
    .setPrettyPrinting()
    .create()

val user = UserResponse(1, "John", "secret123")
println(gson.toJson(user))
// {"user_id":1,"full_name":"John"} — password excluded

Working with generics

The generics problem in Java and Kotlin is type erasure at compile time. When Gson deserializes List<User>, it does not know the element type and returns List<Map<String, Any>>. To preserve type information, Gson provides TypeToken — an abstract class that captures the type parameter through an anonymous class. Without TypeToken, the developer would have to manually convert each element from Map to the target type, resulting in cumbersome code and performance loss.

TypeToken for lists

TypeToken solves the type erasure problem. The developer creates an anonymous subclass of TypeToken with the required type parameter, and Gson uses the information from the class signature for correct deserialization. TypeToken also works with Map, Set, and any other parameterized types, including nested generics. In particular, for Map<String, List<User>>, a TypeToken with the full nested type signature is required, otherwise Gson deserializes values as List<Map<String, Any>> instead of List<User>.

kotlin
// TypeToken for list deserialization
data class Product(
    val id: Int,
    val title: String,
    val price: Double
)

val jsonArray = """
[
    {"id":1,"title":"Phone","price":599.0},
    {"id":2,"title":"Laptop","price":1299.0}
]
"""

val gson = Gson()
val listType = object : TypeToken<List<Product>>() {}
val products: List<Product> =
    gson.fromJson(jsonArray, listType.type)

// Custom deserializer
class LocalDateAdapter :
    JsonDeserializer<LocalDate> {

    override fun deserialize(
        json: JsonElement,
        typeOfT: java.lang.reflect.Type,
        context: JsonDeserializationContext
    ): LocalDate {
        return LocalDate.parse(json.asString)
    }
}

For custom serialization logic, Gson supports the JsonSerializer and JsonDeserializer interfaces. They are registered via GsonBuilder.registerTypeAdapter() and allow handling types that the library cannot serialize automatically: Java 8 dates, Enums with non-standard values, or third-party classes without source code access. When implementing an adapter, it is important to monitor performance: calling reflection inside a custom adapter negates the advantages of manual control, so direct method and field calls are preferred. In the Gson ecosystem, there is also the gson-extras module, which provides adapters for common types such as UUID, Optional, and Joda-Time date wheels.

Configuration via GsonBuilder

GsonBuilder provides dozens of methods for fine-tuning serialization. setPrettyPrinting adds indentation and line breaks to the output JSON for readability. disableHtmlEscaping disables HTML character escaping in strings. setDateFormat specifies the date format, which is critical when working with servers that use non-standard time representations. setLenient enables lenient parsing mode, which ignores certain JSON formatting errors. addDeserializationExclusionStrategy allows programmatically excluding fields from deserialization based on custom strategies. For debugging, setPrettyPrinting combined with logging is useful — it makes JSON responses readable in logs and simplifies finding mismatches.

An important GsonBuilder feature is versioning field management through @Since and @Until annotations. The developer specifies the object version via setVersion, and Gson automatically includes or excludes fields based on their version annotation. This is useful during API evolution when the same model is used for different versions of the server protocol. GsonBuilder also supports registering TypeAdapterFactory for global family type handling and complexMapKeySerialization for correct work with complex Map keys.

Frequently Asked Questions

What is Gson in Android development?

Gson is a Google library for converting Java objects to JSON and back. It is widely used in Android applications for parsing server responses, serializing requests, and storing data in local storage.

How does Gson handle null values?

By default, Gson skips null fields during serialization. To include null values, use GsonBuilder.serializeNulls(). During deserialization, fields missing in JSON remain null or take the default value for the type.

How is Gson different from Moshi?

Moshi does not use reflection for Kotlin classes, which provides higher performance and predictable behavior. Moshi also correctly handles Kotlin null safety, while Gson may deserialize null into a non-null field, causing an exception.

How does @SerializedName work in Gson?

@SerializedName binds a JSON key to a class field when their names do not match. For example, for the field kotlinName and the JSON key "kotlin_name", the annotation @SerializedName("kotlin_name") ensures correct conversion.

What is TypeToken in Gson?

TypeToken is an abstract class that captures the type parameter through an anonymous class. It is necessary for deserializing collections and other parameterized types, because due to type erasure, Gson cannot recover the element type at runtime.

Summary

  • Gson — Google library for JSON serialization with Java and Kotlin support
  • toJson and fromJson — main methods for serializing and deserializing objects
  • @SerializedName — annotation for mapping fields to JSON keys when names do not match
  • @Expose — field visibility control during serialization via GsonBuilder
  • TypeToken — solving type erasure for parameterized collections
  • GsonBuilder — configuration of formatting, versioning, dates and custom adapters
  • JsonSerializer/JsonDeserializer — interfaces for handling types with non-standard logic

We will develop a mobile application turnkey

IT Sectr creates iOS and Android applications for startups and businesses since 2017. We will advise you and propose the best solution.

Discuss the project

Read also