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 = 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)
}All lessons in this course
- kotlinx.serialization Setup
- Serializable Classes
- JSON Encoding and Decoding
- Custom Serializers