JSON serialization overview
The Kotlin serialization library allows you to easily convert Kotlin objects to JSON and back. The Json class is the primary tool for this, offering flexibility in how JSON is generated and parsed. You can configure Json instances to handle specific JSON behaviors or use its default instance for basic tasks.
With the Json class, you can:
Serialize Kotlin objects to JSON strings using the
encodeToString()function.Deserialize JSON strings back to Kotlin objects with the
decodeFromString()function.Work directly with the
JsonElementwhen handling complex JSON structures using theencodeToJsonElement()and thedecodeFromJsonElement()functions.Use Experimental extension functions to serialize and deserialize I/O sources without creating intermediate strings, including JVM streams as well as
kotlinx-ioand Okio types.
Before you start, import the following declarations from the serialization library:
Here's a simple example that uses the default Json instance to show how JSON serialization works in Kotlin:
In addition to using the default configuration, you can customize the Json instance for specific use cases, such as ignoring unknown keys:
What's next
Learn how to customize
Jsoninstances to address different use cases for serialization and deserialization.Explore advanced JSON element handling to manipulate and work with JSON data before it is parsed or serialized.
Discover how to transform JSON during serialization and deserialization for more control over your data.