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.
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
(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
(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)
@Serializabletells the plugin to generate the conversion for this class.- Defaults make a key optional. (blog sources)
bodyhas a default, so JSON without abodykey 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
NoteEntityandNotefor the same reason as in Chapter 5.
The Json Instance, Decoding and Encoding
(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.
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:
(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.
A Test You Can Run Without a Phone
(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?
| Gson | Moshi | kotlinx.serialization | |
|---|---|---|---|
| Written for | Java | Java and Kotlin | Kotlin only |
| How it works | Reflection | Reflection or generated code | A compiler plugin generates the code |
| Knows Kotlin defaults and non-null types | Not reliably | With its Kotlin support | Yes: defaults make keys optional |
| Unknown keys | Ignored | Ignored | An 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.
Try It Yourself
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.
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.
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".
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).
Json through a converter, and shows loading, success and error states, with the repository writing what it fetches into Room.