Skip to content
Tutorials Center
My learning

Topics

Lesson 74 of 104 ยท Networking

JSON with kotlinx.serialization and Moshi

Parse JSON on Android with kotlinx.serialization and Moshi: DTOs, unknown keys, nullable and default fields, converters and DTO to domain mapping.

A server sends text; your app wants objects. Turning JSON into Kotlin classes is called deserialization, and doing it well is less about the library than about three decisions: what shape your DTO classes have, how strict the parser should be about surprises, and where the mapping to your own domain types happens. Servers add fields, send null where you did not expect it and omit values that were "always there" last week, and your app must survive that.

This lesson applies kotlinx.serialization in an Android networking setting and compares it with Moshi, the other popular choice. The Android library setup is read-only. The compiler plugin that generates the serializers cannot run on the site, so the TryIt blocks are Kotlin stand-ins: a small hand-written JSON parser and decoder that reproduces the rules (missing fields, unknown keys, nulls, defaults, strictness) so you can watch each one.

DTOs: a class for the wire

A DTO (data transfer object) mirrors the JSON exactly, names and all. It is separate from the model your UI uses, so a change in the API does not ripple through your screens:

Kotlin
// read-only example: needs the serialization plugin
@Serializable
data class UserDto(
    val id: Long,
    val name: String,
    @SerialName("avatar_url") val avatarUrl: String? = null,
    val active: Boolean = true,
    val roles: List<String> = emptyList()
)

@SerialName maps a JSON key like avatar_url to a Kotlin property in camelCase. The default values and the nullable type are the contract with the server: id and name are required, while avatarUrl, active and roles may be missing. If a required field is missing from the JSON, decoding fails with a SerializationException, and that is usually what you want: a loud failure at the network boundary beats a null that crashes three screens later.

Configuring the parser

The Json instance decides how forgiving decoding is. Create one and reuse it:

Kotlin
// read-only example: needs kotlinx.serialization
val json = Json {
    ignoreUnknownKeys = true      // new server fields must not break old apps
    coerceInputValues = true      // null or unknown enum value -> property default
    explicitNulls = false         // do not write null fields when encoding
    isLenient = false             // keep strict JSON syntax
}

ignoreUnknownKeys = true is the most important setting for apps. Old app versions stay installed for years, and the server will add fields. By default kotlinx.serialization is strict and throws on a key it does not know. coerceInputValues turns a null for a non-nullable property that has a default into that default, which tolerates sloppy backends without making every property nullable. Do not use it to hide bugs in required fields; those have no default and still fail.

Hook the parser into Retrofit with a converter factory. Retrofit 3 includes one, and older versions use a separate artifact with the same name:

Kotlin
// read-only example: needs Retrofit and kotlinx.serialization
val retrofit = Retrofit.Builder()
    .baseUrl("https://api.example.com/v1/")
    .client(okHttp)
    .addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
    .build()

For one-off parsing, call json.decodeFromString<UserDto>(text) directly, or json.decodeFromString<List<UserDto>>(text) for a JSON array.

The first TryIt is a stand-in for the decoding rules. A compact parser turns text into maps and lists, and decodeUser mimics the generated serializer under two settings. Run it and compare how the same payloads behave when strict and when tolerant.

Kotlin Decoding rules: missing, unknown and null fields (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The real generated serializers are also faster and handle escapes, numbers of all sizes, nested objects and polymorphism. The stand-in only captures the decisions you configure.

Moshi

Moshi is Square's JSON library, built to go with Retrofit. For Kotlin it uses codegen, so no reflection is needed:

Kotlin
// read-only example: needs Moshi and its KSP processor
@JsonClass(generateAdapter = true)
data class UserDto(
    val id: Long,
    val name: String,
    @Json(name = "avatar_url") val avatarUrl: String? = null,
    val active: Boolean = true
)

val moshi = Moshi.Builder().build()

val retrofit = Retrofit.Builder()
    .baseUrl("https://api.example.com/v1/")
    .addConverterFactory(MoshiConverterFactory.create(moshi))
    .build()

Moshi's behavior is close to the strict setup above, with two differences that matter. It ignores unknown keys by default, and it throws JsonDataException when a non-null property is missing or null and has no default. It also respects Kotlin default values with generated adapters. The choice between the two is mostly taste and platform: kotlinx.serialization works on every Kotlin target and understands Kotlin features such as sealed classes natively, while Moshi is Android and JVM focused with a long track record. Pick one per app; mixing them only adds dependencies.

Whichever you use, keep these rules:

  • Model absence with a nullable type or a default, never with a magic value like -1.
  • Use Long for ids and String for anything that could outgrow an Int or lose leading zeros.
  • Send dates as ISO 8601 strings and parse them with java.time after decoding, or a custom serializer.
  • Make unknown enum values safe with a fallback entry (UNKNOWN) plus coerceInputValues, or a custom serializer.

From DTO to domain model

The DTO is the shape of the wire. Your UI and business logic should use a domain model that is shaped for them: no nullable fields that are never null in practice, real types instead of strings, names that make sense in the app. A small mapper function sits between them and is the only place that knows both:

Kotlin
// read-only example: plain Kotlin
data class User(val id: Long, val displayName: String, val avatar: Avatar, val isAdmin: Boolean)

sealed interface Avatar {
    data class Remote(val url: String) : Avatar
    data object Initials : Avatar
}

fun UserDto.toDomain() = User(
    id = id,
    displayName = name.trim(),
    avatar = avatarUrl?.let { Avatar.Remote(it) } ?: Avatar.Initials,
    isAdmin = "admin" in roles
)

This keeps API quirks, such as a renamed field, in one function. It also lets you test mapping rules without a network and keeps @Serializable out of your domain layer, a point that returns in The Repository Pattern and Data Sources.

The second TryIt runs the whole pipeline in the stand-in world: fake JSON payloads go through the decoder and the mapper, and a screen-ready list comes out. A payload that fails decoding becomes an error entry instead of crashing the loop, the way a repository would turn it into a Result.

Kotlin From JSON text to domain models (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Real apps decode with the generated serializer first and use the same mapping style afterwards. Handling the failures properly, with typed errors and retries, is the topic of Error Handling and Offline-first.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is ignoreUnknownKeys = true recommended for mobile apps?

    You cannot force users to update. The server will add fields over time, so a tolerant parser keeps old installs working.
  2. 2. A DTO property has no default and is non-null, and the JSON omits it. What happens with kotlinx.serialization?

    A required field that is missing cannot be filled in, so decoding fails. Give a property a default or a nullable type when absence is allowed.
  3. 3. What is the main reason to map a DTO to a separate domain model?

    The DTO mirrors the server. The domain model fits the app. A mapper function is the single place that knows both, so API changes stay local.
  4. 4. What does @SerialName("avatar_url") do on a property called avatarUrl?

    It changes only the name used in JSON, so you can keep idiomatic camelCase in Kotlin while matching a snake_case API.
  5. 5. Which statement about Moshi is correct?

    Moshi's generated adapters skip unknown keys by default and report a missing required value with JsonDataException. It plugs into Retrofit with MoshiConverterFactory.

Summary

  • A DTO mirrors the JSON; @SerialName (or Moshi's @Json) bridges naming styles, and defaults or nullable types express optional fields.
  • Configure one shared Json instance with ignoreUnknownKeys = true, and consider coerceInputValues for tolerant handling of nulls and unknown enum values.
  • A missing required field should fail loudly at the boundary, not turn into a bug elsewhere.
  • Moshi with codegen is the other mainstream option; pick one library per app and plug it into Retrofit with a converter factory.
  • Map DTOs to domain models in a small, testable function, so wire changes stay in one place.
  • The library setup is read-only here; the TryIt blocks use a hand-written decoder as a stand-in for the generated serializers.

Next: Error Handling and Offline-first