JSON Encoding and Decoding
Convert to and from JSON.
JSON Encoding and Decoding is a free Kotlin Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, and your progress syncs across the web and the CoddyKit app. The Kotlin Academy course includes 4 lessons in total.
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.
Learn Kotlin with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 51
- Lessons
- 203
Frequently Asked Questions
Is the “JSON Encoding and Decoding” lesson free?
Yes — any 3 lessons of the Kotlin Academy learning path, including “JSON Encoding and Decoding”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Kotlin Academy course includes 4 lessons in total.
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, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.
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