0Pricing
Kotlin Academy · Lesson

JSON Encoding and Decoding

Convert to and from JSON.

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 = Json

Encoding 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)
}

All lessons in this course

  1. kotlinx.serialization Setup
  2. Serializable Classes
  3. JSON Encoding and Decoding
  4. Custom Serializers
← Back to Kotlin Academy