Kotlin Serialization and JSON

Android Development with Compose: Architecture & Data

Course 5 ยท Chapter 6 ยท Turning Text Into Objects

Servers speak JSON: plain text that describes data. Your app speaks Kotlin classes. kotlinx.serialization is Kotlin's own library for converting between the two. This chapter is deliberately about the library on its own, with no network involved, so that when Chapter 7 adds Retrofit the only new thing is the request.

What was checked, and how: read this first
Checked in official Kotlin docs (one search limited to kotlinlang.org and GitHub, summaries only): strict decoding is the default, so an unknown key is an error; ignoreUnknownKeys = true on a Json instance skips unknown keys; a @JsonIgnoreUnknownKeys annotation exists for one class, is experimental and needs an opt-in; decodeFromString decodes a JSON string using the deserializer for the type; and decoding failures come as a JsonDecodingException, part of a hierarchy under SerializationException. Checked only in unofficial blog posts and Q&A (an earlier, unrestricted search): @SerialName for keys that differ, defaults making a key optional, and that Retrofit needs a separate converter. Not found in any source: the Gradle plugin id and setup, encodeToString, prettyPrint, catching IllegalArgumentException, and the Gson and Moshi comparison. Those are general knowledge. All code is unrun (no Kotlin compiler on the machine used to write this); nothing was seen on your install.

What JSON Looks Like

{ "userId": 1, "id": 7, "title": "Buy milk", "body": "Semi-skimmed, two litres" }

(general knowledge) Curly braces hold an object, square brackets a list, and keys are always in quotes. Values are strings, numbers, true or false, null, objects or lists. This sample is in the shape of the free test service the next chapter uses; its exact fields get re-checked there.

Setup

// Module build.gradle.kts (versions are placeholders) plugins { id("org.jetbrains.kotlin.plugin.serialization") version "<kotlin-version>" } dependencies { implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:<serialization-version>") }

(general knowledge, not found in the searches) Serialization needs two things: a compiler plugin that generates the conversion code for classes you mark, and the runtime library with the JSON format. The plugin version follows your Kotlin version, so take both from the official setup page for the Kotlin version your project uses (Chapter 4 noted the generated project uses AGP 9.x and Kotlin 2.2).

A Serializable Class (a DTO)

import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class RemoteNoteDto( val id: Long, val title: String, val body: String = "", // optional: has a default @SerialName("userId") val authorId: Long? = null // JSON key differs from the Kotlin name )
  • @Serializable tells the plugin to generate the conversion for this class.
  • Defaults make a key optional. (blog sources) body has a default, so JSON without a body key still decodes. A property with no default is required.
  • @SerialName (blog sources) maps a JSON key to a Kotlin property with a different name; common for snake_case keys.
  • "DTO" means data transfer object (general knowledge): a class shaped like the network data, kept separate from NoteEntity and Note for the same reason as in Chapter 5.

The Json Instance, Decoding and Encoding

import kotlinx.serialization.json.Json // One shared instance, configured once val json = Json { ignoreUnknownKeys = true prettyPrint = true // only affects encoding }
val note: RemoteNoteDto = json.decodeFromString<RemoteNoteDto>(text) val notes: List<RemoteNoteDto> = json.decodeFromString<List<RemoteNoteDto>>(listText) val backToText: String = json.encodeToString(note)

(docs) decodeFromString uses the deserializer for the type you ask for. (general knowledge) encodeToString goes the other way. Unknown keys: the sample has a userId key; because the DTO maps it, it works. A key the DTO does not mention is an error by default; (docs) ignoreUnknownKeys = true skips it. That is the setting you almost always want for a server you do not control, because servers add fields.

// Without ignoreUnknownKeys, Json is strict: an unknown key is an error (docs). // A per-class alternative exists but is experimental and needs an opt-in: @OptIn(ExperimentalSerializationApi::class) @JsonIgnoreUnknownKeys @Serializable data class LenientDto(val id: Long)

When the Data Is Bad

A missing required key, a string where a number should be, or text that is not JSON at all will fail. (docs) The failure comes as a JsonDecodingException, a kind of SerializationException. Catch it where you decode, and turn it into a result the rest of the app can handle:

import kotlinx.serialization.SerializationException fun parseNotes(text: String): Result<List<RemoteNoteDto>> = try { Result.success(json.decodeFromString<List<RemoteNoteDto>>(text)) } catch (e: SerializationException) { Result.failure(e) // bad or unexpected JSON } catch (e: IllegalArgumentException) { Result.failure(e) // a value the type could not accept }

(general knowledge) A value the type cannot accept can surface as IllegalArgumentException instead, which is why both are caught here. This matches Chapter 3's advice to catch exceptions in coroutines rather than let the app crash.

// The DTO is the network shape; map it to the storage class (Chapter 5's rule again) fun RemoteNoteDto.toEntity() = NoteEntity(id = id, text = title)

A Test You Can Run Without a Phone

// app/src/test/.../RemoteNoteDtoTest.kt (a plain JVM test) class RemoteNoteDtoTest { @Test fun unknownKeysAreIgnored() { val text = "{\"id\":1,\"title\":\"Hi\",\"extra\":true}" val note = json.decodeFromString<RemoteNoteDto>(text) assertEquals("Hi", note.title) assertEquals("", note.body) // the default was used } @Test(expected = SerializationException::class) fun missingRequiredFieldFails() { json.decodeFromString<RemoteNoteDto>("{\"id\":1}") } }

(general knowledge) Parsing is plain Kotlin, so this runs as an ordinary unit test on your computer. It is the quickest way to try the library, and to see the error messages.

Gson, Moshi or kotlinx.serialization?

GsonMoshikotlinx.serialization
Written forJavaJava and KotlinKotlin only
How it worksReflectionReflection or generated codeA compiler plugin generates the code
Knows Kotlin defaults and non-null typesNot reliablyWith its Kotlin supportYes: defaults make keys optional
Unknown keysIgnoredIgnoredAn error unless ignoreUnknownKeys (docs)

The Gson and Moshi columns, and the "how it works" row, are (general knowledge, not checked) and are a summary of common experience, not a benchmark. All three are used in real apps. The older course used Gson or Moshi; this course uses kotlinx.serialization because it is Kotlin-first and its strictness makes bad data visible instead of silent.

Compared with the Classic UI course
This chapter has no counterpart in Android Development: Architecture & Data. That course covered JSON inside its Retrofit chapter (Android Development: Architecture & Data 4), using Gson or Moshi. Splitting it out here means Chapter 7 can concentrate on the network call.

Try It Yourself

Exercise 1

Add the plugin and library, create RemoteNoteDto and the json instance, and write the unit test from the chapter. Report the Kotlin, plugin and library versions you used, and whether the test passed.

๐Ÿ“„ View solution
Exercise 2

Break the decoding on purpose three ways: remove ignoreUnknownKeys, drop a required key, and put text where a number should be. Write down the exception type and message each time, and which one you would show a user.

๐Ÿ“„ View solution
Exercise 3

Add a createdAt property mapped from the JSON key created_at with @SerialName, make it nullable, and decode JSON with and without it. Explain when you would choose "nullable" and when "a default value".

๐Ÿ“„ View solution
Not Yet Verified
Checked in official Kotlin docs (summaries only): strict by default; ignoreUnknownKeys; the experimental @JsonIgnoreUnknownKeys with an opt-in; decodeFromString; JsonDecodingException under SerializationException.
Unofficial sources only: @SerialName; defaults making keys optional; Retrofit needing a separate converter (Chapter 7 checks this).
General knowledge, not found in any search: the Gradle plugin id and setup; encodeToString and prettyPrint; catching IllegalArgumentException; the Gson, Moshi and kotlinx comparison; what JSON looks like; the sample's resemblance to the test service.
Not verified: every listing and solution (unrun); the exercises (not run by me). Nothing was checked on your install.
Sources: JSON serialization overview (kotlinlang.org), Customize the Json instance (kotlinlang.org), ignoreUnknownKeys API reference (kotlinlang.org), JsonIgnoreUnknownKeys API reference (kotlinlang.org), Introduction to using Kotlin Serialization (ProAndroidDev, blog).
Coming up
Chapter 7 makes the network call with Retrofit, uses this chapter's Json through a converter, and shows loading, success and error states, with the repository writing what it fetches into Room.