Which Kotlin JSON library should you choose?
For a new Kotlin-first project, start with kotlinx.serialization: its compiler plugin generates serializers and it supports Kotlin Multiplatform. For an existing Gson app, keep Gson and generate its field annotations. Moshi fits projects already using its adapters, especially Android apps. Plain Kotlin output contains models only; you still need a serializer or a manual mapping layer.
| Library | JSON key mapping | Setup |
|---|---|---|
| kotlinx.serialization | @SerialName | Serialization compiler plugin + JSON library |
| Gson | @SerializedName | Gson dependency |
| Moshi | @Json | Kotlin reflection adapter or generated adapter |
The converter infers models from the examples you provide, not the API's complete schema. Include nested objects, populated lists and nullable values that represent real responses. A single sample with a missing field cannot reveal that field's type. An empty array does not reveal its element type either; add a representative element before generating.
Run the examples
Each example below is a complete Main.kt for a Kotlin/JVM console application. Use JDK 17 and Kotlin 2.2.21. Add the matching dependency to your Gradle Kotlin DSL build, put Main.kt under src/main/kotlin, and run ./gradlew run. The checks fail if decoding or re-encoding breaks the demonstrated contract.
plugins {
kotlin("jvm") version "2.2.21"
application
// Add for the kotlinx.serialization example only:
kotlin("plugin.serialization") version "2.2.21"
}
repositories { mavenCentral() }
kotlin { jvmToolchain(17) }
application { mainClass.set("MainKt") }
kotlinx.serialization: Kotlin-first JSON
Mark every serializable model with @Serializable, including nested Address. @SerialName connects displayName to display_name without changing the wire format. encodeDefaults includes the default null nickname when encoding. Without it, the default-valued property can be omitted. Keep the serialization plugin version aligned with the Kotlin compiler.
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0")
}import kotlinx.serialization.Serializable
import kotlinx.serialization.SerialName
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
@Serializable
data class Address(val city: String)
@Serializable
data class User(
val id: Long,
@SerialName("display_name") val displayName: String,
val tags: List<String>,
val address: Address,
val nickname: String? = null
)
fun main() {
val input = """{"id":7,"display_name":"Ada","tags":["kotlin"],"address":{"city":"Oslo"},"nickname":null}"""
val json = Json { encodeDefaults = true }
val user = json.decodeFromString<User>(input)
check(user.displayName == "Ada" && user.address.city == "Oslo")
check(json.decodeFromString<User>("""{"id":7,"display_name":"Ada","tags":[],"address":{"city":"Oslo"}}""").nickname == null)
check(Json.parseToJsonElement(json.encodeToString(user)) == Json.parseToJsonElement(input))
println(json.encodeToString(user))
}Gson: use existing Gson models
Gson uses @SerializedName for wire keys. serializeNulls emits the explicit null in this example; Gson omits null-valued object properties by default. Gson reflection does not enforce Kotlin non-null constructor contracts in the same way as Kotlin-aware serializers. Validate required response fields before using them: a missing field can leave a non-null Kotlin property holding null. A nullable declaration alone does not make Gson validate the rest of a response.
dependencies {
implementation("com.google.code.gson:gson:2.13.2")
}import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
data class Address(val city: String)
data class User(
val id: Long,
@SerializedName("display_name") val displayName: String,
val tags: List<String>,
val address: Address,
val nickname: String? = null
)
fun main() {
val input = """{"id":7,"display_name":"Ada","tags":["kotlin"],"address":{"city":"Oslo"},"nickname":null}"""
val gson = com.google.gson.GsonBuilder().serializeNulls().create()
val user = gson.fromJson(input, User::class.java)
check(user.displayName == "Ada" && user.tags == listOf("kotlin"))
check(com.google.gson.JsonParser.parseString(gson.toJson(user)) == com.google.gson.JsonParser.parseString(input))
println(gson.toJson(user))
}Moshi: Kotlin-aware reflection adapters
This runnable example uses KotlinJsonAdapterFactory, not code generation, so it needs no KSP setup. @Json preserves display_name. addLast lets explicitly registered adapters take precedence over the Kotlin factory. If you choose generated adapters instead, configure Moshi codegen with a compatible KSP version and use @JsonClass(generateAdapter = true); annotations without the generated adapter are not a complete setup.
dependencies {
implementation("com.squareup.moshi:moshi-kotlin:1.15.2")
}import com.squareup.moshi.Json
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
data class Address(val city: String)
data class User(
val id: Long,
@Json(name = "display_name") val displayName: String,
val tags: List<String>,
val address: Address,
val nickname: String? = null
)
fun main() {
val input = """{"id":7,"display_name":"Ada","tags":["kotlin"],"address":{"city":"Oslo"},"nickname":null}"""
val moshi = Moshi.Builder().addLast(KotlinJsonAdapterFactory()).build()
val adapter = moshi.adapter(User::class.java).serializeNulls()
val user = requireNotNull(adapter.fromJson(input))
check(user.displayName == "Ada" && user.address.city == "Oslo")
check(adapter.fromJson(adapter.toJson(user)) == user)
check(requireNotNull(adapter.fromJson("""{"id":7,"display_name":"Ada","tags":[],"address":{"city":"Oslo"}}""")).nickname == null)
println(adapter.toJson(user))
}Nullable, optional and missing are different
A nullable String? allows the JSON value null. A default value such as val nickname: String? = null also allows the key to be absent with kotlinx.serialization and Moshi. A required val name: String should be present and non-null. Do not enable “all properties optional” just to hide a server contract error: decide which fields your app really can operate without.
For kotlinx.serialization, a missing required field raises MissingFieldException. Wrong scalar types or malformed input produce serialization errors. Unknown keys fail by default; use Json { ignoreUnknownKeys = true } when your client deliberately accepts additive API fields. Moshi ignores unknown fields by default; use adapter.failOnUnknown() to reject them. Gson also ignores unknown fields. Choose that behavior intentionally for your API, rather than assuming all libraries validate alike.
Arrays, numbers and dates
A JSON array becomes List<T>. For a top-level array with kotlinx.serialization, decode List<User> instead of User. With Gson, use an object : TypeToken<List<User>>() {}.type to retain the generic type. With Moshi, construct Types.newParameterizedType(List::class.java, User::class.java) and request that adapter. Do not decode a list as a single object.
Use Long for whole-number IDs that fit signed 64-bit integers, Double for ordinary fractional measurements, and a deliberate decimal representation when exact money arithmetic matters. JSON has no date type: an ISO 8601 timestamp is a string until you explicitly map it to a date using a serializer or adapter. An array containing unrelated object shapes may need a sealed hierarchy and a discriminator; a generated model from one response cannot establish those rules.
From generated code to a working API client
- Copy a representative response without credentials or customer details.
- Select the library already used in your project and a clear root model name.
- Generate, then review the inferred nullability and number types.
- Add that library's dependency and any compiler plugin or adapter factory.
- Decode a fixture, assert the fields your application needs and encode it back if your app sends the same model.
The converter provides repeatable, library-specific models immediately in your browser, with copy and download available alongside the result. Modern output never posts your JSON to our server. Compatibility mode uses our existing server converter and supports Gson or plain Kotlin only. Choose Modern for kotlinx.serialization and Moshi.
Why does my JSON key have a different Kotlin name?
Keys such as display_name are commonly mapped to displayName for Kotlin style. Keep the library annotation: removing it changes which wire key the decoder expects. Reserved words and unusual characters need safe identifiers too. Plain Kotlin has no mapping annotations, so verify any downstream mapper before using renamed properties.
Back to the JSON to Kotlin converter · Open Kotlin in the Workbench