JSON Encoding and Decoding
Convert to and from JSON.
JSON Encoding and Decoding is a free Kotlin Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
The Json Object
The Json object is the core of encoding and decoding. The default instance is ready to use, or you can build a configured one.
import kotlinx.serialization.json.Json
val json = JsonEncoding to a String
Use encodeToString to turn an object into a JSON string.
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
@Serializable
data class Book(val title: String, val pages: Int)
fun main() {
val book = Book("Kotlin in Action", 360)
val text = Json.encodeToString(book)
println(text)
}Decoding from a String
Use decodeFromString to parse JSON back into an object. The target type is inferred or given explicitly.
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
@Serializable
data class Book(val title: String, val pages: Int)
fun main() {
val text = "{\"title\":\"Atomic Kotlin\",\"pages\":500}"
val book = Json.decodeFromString<Book>(text)
println(book.title)
}Encoding Lists
Collections encode automatically. A list of serializable objects becomes a JSON array.
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
@Serializable
data class Tag(val name: String)
fun main() {
val tags = listOf(Tag("kotlin"), Tag("json"))
println(Json.encodeToString(tags))
}Pretty Printing
Configure a Json { } builder to enable indented output, useful for logging and debugging.
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
@Serializable
data class Point(val x: Int, val y: Int)
val pretty = Json { prettyPrint = true }
fun main() {
println(pretty.encodeToString(Point(1, 2)))
}Ignoring Unknown Keys
By default decoding fails if JSON contains keys not in your class. Set ignoreUnknownKeys = true to skip them — handy for evolving APIs.
import kotlinx.serialization.json.Json
val lenient = Json { ignoreUnknownKeys = true }Encoding Defaults
By default, properties equal to their default value are not written. Enable encodeDefaults = true to always include them.
import kotlinx.serialization.json.Json
val withDefaults = Json { encodeDefaults = true }Working with JsonElement
For dynamic JSON you can parse into a JsonElement tree instead of a typed class.
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
fun main() {
val element: JsonElement = Json.parseToJsonElement("{\"a\":1}")
println(element)
}Reading JsonObject Fields
Cast a JsonElement to JsonObject and access fields by key, then convert primitives.
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.int
fun main() {
val obj = Json.parseToJsonElement("{\"a\":1}").jsonObject
val a = obj["a"]!!.jsonPrimitive.int
println(a)
}Round-Tripping
Encode then decode should give back an equal object (a round trip). This is a great way to sanity-check your model.
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
@Serializable
data class P(val x: Int)
fun main() {
val original = P(42)
val back = Json.decodeFromString<P>(Json.encodeToString(original))
println(original == back)
}Common Decoding Errors
Watch for these runtime exceptions:
SerializationException: Unexpected JSON token— malformed JSON- Missing required field — JSON lacks a non-default property
- Unknown key — disable strictness with
ignoreUnknownKeys
Quick Check
Your API frequently adds new JSON fields. Which config keeps decoding from breaking?
Recap
You can now move between objects and JSON:
encodeToString/decodeFromString- Configure with
Json { }:prettyPrint,ignoreUnknownKeys,encodeDefaults - Parse dynamic JSON via
JsonElement
Next: custom serializers for unsupported types.
Frequently asked questions
Is the “JSON Encoding and Decoding” lesson free?
Yes — the full text of “JSON Encoding and Decoding” is free to read here on the web, and the Kotlin Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Kotlin Academy course, upgrade to CoddyKit PRO.
What will I learn in “JSON Encoding and Decoding”?
Convert to and from JSON. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Kotlin Academy?
No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “JSON Encoding and Decoding” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Kotlin Academy lesson?
Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- kotlinx.serialization Setup
- Serializable Classes
- JSON Encoding and Decoding
- Custom Serializers