Kotlin example

How to parse JSON into a data class in Kotlin

9 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

With Gson, call Gson().fromJson(json, User::class.java) for one object and pass object : TypeToken<List<User>>() {}.type for a list. Gson doesn't know about Kotlin's null safety: a field missing from the JSON leaves a non-null property null, so give every property a default or make it nullable. In your own project, kotlinx.serialization with @Serializable is the Kotlin-native alternative.

Kotlin has no JSON parser in its standard library, so you pick a library. The examples here use Gson (com.google.gson), which is on this page's classpath and is what most older answers use. kotlinx.serialization, JetBrains' own library, is the more modern choice because it respects default values and non-null types, but it needs a compiler plugin and a dependency, so it isn't available here; the FAQ shows its shape. The sections cover one object, a list with TypeToken, the missing-field and default-value traps, JSON names that differ from your properties, writing JSON back out, and walking a JSON tree with no class at all, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1Gson: fromJson into a data classRecommended

Declare a data class whose property names match the JSON keys, then hand Gson the text and the class: gson.fromJson(json, User::class.java). Gson matches keys to properties by name, fills nested objects from nested data classes, and reads List<String> properties without extra work, because the element type is in the property's declaration. Keys with no matching property are ignored. Malformed JSON throws JsonSyntaxException. A Gson instance is thread-safe, so create one and reuse it.

DataClassFromJson.kt
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException

data class Address(val city: String, val zip: String)

data class User(
    val name: String,
    val age: Int,
    val tags: List<String>,
    val address: Address,
)

fun main() {
    val gson = Gson()
    val json = "{\"name\":\"Ann\",\"age\":31,\"tags\":[\"admin\",\"dev\"]," +
        "\"address\":{\"city\":\"Oslo\",\"zip\":\"0150\"},\"extra\":true}"

    // Pass the class: Gson fills each property from the key of the same name
    val user = gson.fromJson(json, User::class.java)
    println(user)
    println("${user.name} (${user.age}) lives in ${user.address.city}")
    println(user.tags.joinToString(" + "))

    // Broken JSON throws JsonSyntaxException
    try {
        gson.fromJson("{\"name\":\"Ann\",", User::class.java)
    } catch (e: JsonSyntaxException) {
        println(e.message)
    }
}

Output

The data class prints as User(name=Ann, age=31, tags=[admin, dev], address=Address(city=Oslo, zip=0150)): the nested address object became an Address, the array a List<String>, and the unknown extra key was dropped without complaint. zip stays the text 0150 because the property is a String. The cut-off JSON fails with java.io.EOFException: End of input at line 1 column 15 path $.name, and the path tells you where the parser gave up. Coming from Java, there is no User.class: Kotlin writes it User::class.java.

2A list of objects: TypeToken

List<User>::class.java doesn't exist: on the JVM the <User> part is erased at runtime, and List::class.java tells Gson nothing about the elements. The fix is an anonymous subclass, object : TypeToken<List<User>>() {}, whose .type keeps the full generic type. Gson 2.10 and later also accept the token itself, without .type. In Kotlin you can hide the token behind a reified helper, so the target type comes from the variable you assign to. The same works for a Map<String, Int>.

ListWithTypeToken.kt
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

data class User(val name: String, val age: Int)

// reified keeps T at runtime, so one helper covers every type
inline fun <reified T> Gson.fromJson(json: String): T =
    fromJson(json, object : TypeToken<T>() {}.type)

fun main() {
    val gson = Gson()
    val json = "[{\"name\":\"Ann\",\"age\":31},{\"name\":\"Bo\",\"age\":25}]"

    // The anonymous TypeToken subclass keeps List<User> past erasure
    val type = object : TypeToken<List<User>>() {}.type
    val users: List<User> = gson.fromJson(json, type)
    println(users)
    println(users.sumOf { it.age })

    // The reified helper: the type comes from the variable
    val again: List<User> = gson.fromJson(json)
    println(again.map { it.name })
    val counts: Map<String, Int> = gson.fromJson("{\"a\":1,\"b\":2}")
    println(counts)

    // List::class.java alone: Gson does not know the element type
    val raw = gson.fromJson(json, List::class.java)
    println(raw)
    try {
        @Suppress("UNCHECKED_CAST")
        val first = (raw as List<User>)[0]
        println(first.name)
    } catch (e: ClassCastException) {
        println(e.message?.substringBefore(" ("))
    }
}

Output

With the token, Gson returns real User objects, so sumOf { it.age } gives 56, and the reified helper gives the same list and {a=1, b=2} for the map. Without it, the list prints as [{name=Ann, age=31.0}, {name=Bo, age=25.0}]: each element is a Gson LinkedTreeMap and every number has turned into a Double. The cast to List<User> compiles, but reading an element fails with class com.google.gson.internal.LinkedTreeMap cannot be cast to class User, the error behind many Stack Overflow questions.

3Missing fields and default values

This is the trap behind most "Gson and Kotlin" questions. When a class has no constructor without parameters, Gson doesn't call the Kotlin constructor at all: it allocates the object empty and sets the fields it finds in the JSON. So the null checks Kotlin puts in the constructor never run, a missing String stays null, a missing Int is 0, and default values are ignored. Kotlin adds a no-argument constructor only when every constructor parameter has a default; then Gson calls it and the defaults stay. An explicit null in the JSON still gets through either way, so properties that may be absent are safest as nullable types.

MissingFields.kt
import com.google.gson.Gson

data class Contact(val name: String, val email: String)

// host has no default, so there is no no-argument constructor
data class Server(
    val host: String,
    val port: Int = 8080,
    val tls: Boolean = true,
)

// Every property has a default: Kotlin adds a no-argument constructor
data class Settings(val host: String = "localhost", val port: Int = 8080)

// The safe shape for optional fields: nullable with a null default
data class Profile(val name: String? = null, val email: String? = null)

fun main() {
    val gson = Gson()

    // email is missing, yet its type says String
    val contact = gson.fromJson("{\"name\":\"Ann\"}", Contact::class.java)
    println(contact)
    try {
        println(contact.email.length)
    } catch (e: NullPointerException) {
        println(e.message)
    }

    // No constructor call: the defaults 8080 and true are lost
    println(gson.fromJson("{\"host\":\"db\"}", Server::class.java))

    // With a no-argument constructor the defaults stay
    println(gson.fromJson("{\"host\":\"db\"}", Settings::class.java))
    println(gson.fromJson("{}", Settings::class.java))

    // An explicit null still lands in a non-null property
    println(gson.fromJson("{\"host\":null}", Settings::class.java))

    // Nullable properties make the compiler ask for a fallback
    val profile = gson.fromJson("{\"name\":\"Ann\"}", Profile::class.java)
    println(profile.email ?: "no email")
}

Output

Contact(name=Ann, email=null) is a value the type system says can't exist. Nothing fails at parse time; the crash comes later, wherever the property is used: Cannot invoke "String.length()" because the return value of "Contact.getEmail()" is null. Server lost both defaults and printed port=0, tls=false, the JVM's zero values. Settings, where every property has a default, kept port=8080 and even filled localhost for an empty object, but {"host":null} still produced host=null. The nullable Profile is the honest shape: the compiler made the code supply a fallback, which printed no email.

4Different JSON names: @SerializedName

APIs often send snake_case keys such as post_id, while Kotlin properties are camelCase. Put @SerializedName("post_id") on the property to map one name; its alternate list accepts other spellings when parsing. To convert every name the same way, set a naming policy on a GsonBuilder instead. Both work in both directions, so toJson writes the JSON names back.

SerializedName.kt
import com.google.gson.FieldNamingPolicy
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.annotations.SerializedName

data class Post(
    @SerializedName("post_id") val id: Int,
    @SerializedName("created_by", alternate = ["author", "user"])
    val author: String,
)

data class Account(val firstName: String, val lastLogin: Long)

fun main() {
    val gson = Gson()

    // One name at a time with @SerializedName
    val postJson = "{\"post_id\":7,\"created_by\":\"Ann\"}"
    val post = gson.fromJson(postJson, Post::class.java)
    println(post)
    println(gson.fromJson("{\"post_id\":8,\"user\":\"Bo\"}", Post::class.java))
    println(gson.toJson(post))

    // Every name at once with a naming policy
    val snake = GsonBuilder()
        .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
        .create()
    val accountJson = "{\"first_name\":\"Ann\",\"last_login\":1700000000}"
    val account = snake.fromJson(accountJson, Account::class.java)
    println(account)
    println(snake.toJson(account))
}

Output

post_id and created_by land in id and author, and the second post's user key is accepted through alternate. Writing always uses the main name, so toJson gives {"post_id":7,"created_by":"Ann"}. The naming policy maps first_name to firstName and back without any annotation. On a constructor property the annotation needs no @field: prefix, because @SerializedName can only go on a field or a method and Kotlin puts it on the field.

5A data class back to JSON: toJson

gson.toJson(value) works on data classes, lists and maps alike and returns one compact line. Build the Gson with a GsonBuilder to change the output: setPrettyPrinting() for indented JSON, serializeNulls() to keep null properties (by default they are left out), and disableHtmlEscaping() if the output isn't going into HTML, because Gson escapes <, >, &, = and ' by default.

ToJson.kt
import com.google.gson.Gson
import com.google.gson.GsonBuilder

data class Item(val name: String, val price: Double, val note: String? = null)

fun main() {
    val items = listOf(Item("Pen", 1.5), Item("Ink", 4.0, "blue"))

    // Compact by default; null properties are left out
    val gson = Gson()
    println(gson.toJson(items[0]))
    println(gson.toJson(mapOf("count" to 2, "ids" to listOf(1, 2))))

    // Pretty printing, and keeping nulls
    val pretty = GsonBuilder().setPrettyPrinting().serializeNulls().create()
    println(pretty.toJson(items))

    // HTML characters are escaped unless you turn it off
    println(gson.toJson(Item("a<b>", 0.0)))
    val plain = GsonBuilder().disableHtmlEscaping().create()
    println(plain.toJson(Item("a<b>", 0.0)))
}

Output

The first line has no note key at all, because the property was null; the pretty-printed list keeps it as "note": null thanks to serializeNulls() and indents by two spaces. A Double always keeps its decimal point (4.0). The default Gson writes a<b> as a\u003cb\u003e, which is valid JSON that any parser reads back as a<b>; with disableHtmlEscaping() the text stays as typed.

6No data class: JsonParser and JsonArray

When you need one value from a big document, or the shape changes from call to call, skip the classes and read a tree. JsonParser.parseString(json) returns a JsonElement; asJsonObject, getAsJsonArray, asInt and asString walk and convert it. A Gson JsonArray is Iterable, so a plain for loop or map goes through it. A missing key gives null from get, which pairs well with ?..

JsonTree.kt
import com.google.gson.JsonParser

fun main() {
    val json = "{\"total\":2,\"items\":[" +
        "{\"id\":1,\"name\":\"Pen\",\"tags\":[\"office\",\"blue\"]}," +
        "{\"id\":2,\"name\":\"Ink\"}]}"
    val root = JsonParser.parseString(json).asJsonObject
    println(root.get("total").asInt)

    // A JsonArray is Iterable: loop over it like a list
    val items = root.getAsJsonArray("items")
    for (element in items) {
        val item = element.asJsonObject
        val tags = item.getAsJsonArray("tags")?.map { it.asString } ?: listOf()
        println("${item.get("id").asInt} ${item.get("name").asString} $tags")
    }

    // Collection functions work too
    println(items.map { it.asJsonObject.get("name").asString })
    println(items.size())

    // A missing key is null, not an exception
    println(root.get("page"))
    println(root.get("page")?.asInt ?: 1)
    println(items[1].asJsonObject.has("tags"))
}

Output

The loop prints 1 Pen [office, blue] and 2 Ink []: the second item has no tags, so getAsJsonArray returned null and ?: listOf() took over. map on the array gives [Pen, Ink]. Note that the count is items.size(), a method, not the size property of a Kotlin list. The absent page key prints null and falls back to 1. Calling asInt on a missing value without ?. throws a NullPointerException, and on Android the built-in org.json.JSONArray isn't iterable at all (see the FAQ).

7Which should you use?

MethodGivesMissing fieldBest for
gson.fromJson(json, User::class.java)Usernull or 0, even if non-nullOne object; use defaults or nullable properties
object : TypeToken<List<User>>() {}.typeList<User>Same as aboveLists, maps and other generic types
inline fun <reified T> Gson.fromJson(json)Any TSame as aboveHiding the TypeToken in your own code
JsonParser.parseString(json)JsonElement treeget() returns nullA few values, or a shape that changes
gson.fromJson(json, List::class.java)List of LinkedTreeMapNumbers become DoubleAvoid: use a TypeToken
Json.decodeFromString<User>(json)UserException, or the defaultNew projects (kotlinx.serialization, not on this page)

Frequently asked questions

How do I parse JSON with kotlinx.serialization?

Add the serialization plugin and the kotlinx-serialization-json library to your build, mark the class with @Serializable, as in @Serializable data class User(val name: String, val age: Int = 0), and call Json.decodeFromString<User>(json); Json.encodeToString(user) goes the other way. Unlike Gson it calls your constructor, so defaults apply and a missing required field throws MissingFieldException. Unknown keys throw too unless you configure Json { ignoreUnknownKeys = true }. The library is not installed on this page, so the examples here use Gson.

Why does Gson leave a non-null Kotlin property null?

Gson creates the object without calling the Kotlin constructor when the class has no no-argument constructor, then sets only the fields present in the JSON. A missing String stays null and fails later with a NullPointerException, a missing Int is 0, and default values are ignored. Give every property a default (so Kotlin generates a no-argument constructor) or declare the optional ones nullable.

Why does Gson.fromJson return null?

An empty string or the JSON text null makes fromJson return null, even for User::class.java: gson.fromJson("", User::class.java) prints null. Kotlin sees the result as a platform type, so it will not stop you from using it as non-null. If the input can be empty, declare the variable as User? and check it.

How do I iterate through a JSONArray in Kotlin?

Gson's JsonArray is Iterable<JsonElement>, so for (element in array) and array.map { ... } work directly. Android's org.json.JSONArray is not iterable: loop over the indexes with for (i in 0 until array.length()) and read each item with array.getJSONObject(i).

What happens when a JSON value has the wrong type?

Gson converts what it can: a quoted number such as "31" fills an Int property with 31. Text that is not a number throws JsonSyntaxException with the message java.lang.NumberFormatException: For input string: "x", and 31.9 for an Int throws with Expected an int but was 31.9 followed by the position and path. Catch JsonSyntaxException around fromJson when the input comes from outside.

How do I parse JSON into a Map in Kotlin?

Use a TypeToken or the reified helper with the full type: val counts: Map<String, Int> = gson.fromJson(json) gives {a=1, b=2}. With Map::class.java alone, Gson picks the types itself and every number becomes a Double, so the same JSON prints as {a=1.0, b=2.0}.

Run it yourself

Open any of these in the full Kotlin editor to tweak, run and share.

Kotlin playground