0
# Core Serialization
1
2
Core JSON serialization and deserialization functionality providing high-level APIs for converting between Kotlin objects and JSON strings or JsonElements.
3
4
## Capabilities
5
6
### Json Object
7
8
The main entry point for JSON operations, providing both instance methods and a default singleton.
9
10
```kotlin { .api }
11
/**
12
* Main class for JSON serialization and deserialization operations
13
*/
14
sealed class Json : StringFormat {
15
val configuration: JsonConfiguration
16
val serializersModule: SerializersModule
17
18
companion object {
19
val Default: Json
20
}
21
}
22
23
/**
24
* Create a Json instance with custom configuration
25
* @param from Base Json instance to inherit settings from (defaults to Json.Default)
26
* @param builderAction Configuration builder lambda
27
* @return Configured Json instance
28
*/
29
fun Json(from: Json = Json.Default, builderAction: JsonBuilder.() -> Unit): Json
30
```
31
32
### String Serialization
33
34
Convert between Kotlin objects and JSON strings.
35
36
```kotlin { .api }
37
/**
38
* Serialize a value to JSON string using explicit serializer
39
* @param serializer Serialization strategy for type T
40
* @param value Object to serialize
41
* @return JSON string representation
42
*/
43
fun <T> Json.encodeToString(serializer: SerializationStrategy<T>, value: T): String
44
45
/**
46
* Serialize a value to JSON string using reified type
47
* @param value Object to serialize
48
* @return JSON string representation
49
*/
50
inline fun <reified T> Json.encodeToString(value: T): String
51
52
/**
53
* Deserialize JSON string to object using explicit deserializer
54
* @param deserializer Deserialization strategy for type T
55
* @param string JSON string to parse
56
* @return Deserialized object of type T
57
*/
58
fun <T> Json.decodeFromString(deserializer: DeserializationStrategy<T>, string: String): T
59
60
/**
61
* Deserialize JSON string to object using reified type
62
* @param string JSON string to parse
63
* @return Deserialized object of type T
64
*/
65
inline fun <reified T> Json.decodeFromString(string: String): T
66
```
67
68
**Usage Examples:**
69
70
```kotlin
71
import kotlinx.serialization.Serializable
72
import kotlinx.serialization.json.Json
73
74
@Serializable
75
data class Person(val name: String, val age: Int, val city: String?)
76
77
// Serialization
78
val person = Person("Alice", 30, "New York")
79
val jsonString = Json.encodeToString(person)
80
// Result: {"name":"Alice","age":30,"city":"New York"}
81
82
// Deserialization
83
val deserializedPerson = Json.decodeFromString<Person>(jsonString)
84
85
// Custom Json configuration
86
val json = Json {
87
prettyPrint = true
88
ignoreUnknownKeys = true
89
}
90
val prettyJsonString = json.encodeToString(person)
91
```
92
93
### JsonElement Serialization
94
95
Convert between Kotlin objects and JsonElement tree structures for programmatic JSON manipulation.
96
97
```kotlin { .api }
98
/**
99
* Serialize a value to JsonElement using explicit serializer
100
* @param serializer Serialization strategy for type T
101
* @param value Object to serialize
102
* @return JsonElement representation
103
*/
104
fun <T> Json.encodeToJsonElement(serializer: SerializationStrategy<T>, value: T): JsonElement
105
106
/**
107
* Serialize a value to JsonElement using reified type
108
* @param value Object to serialize
109
* @return JsonElement representation
110
*/
111
inline fun <reified T> Json.encodeToJsonElement(value: T): JsonElement
112
113
/**
114
* Deserialize JsonElement to object using explicit deserializer
115
* @param deserializer Deserialization strategy for type T
116
* @param element JsonElement to deserialize
117
* @return Deserialized object of type T
118
*/
119
fun <T> Json.decodeFromJsonElement(deserializer: DeserializationStrategy<T>, element: JsonElement): T
120
121
/**
122
* Deserialize JsonElement to object using reified type
123
* @param json JsonElement to deserialize
124
* @return Deserialized object of type T
125
*/
126
inline fun <reified T> Json.decodeFromJsonElement(json: JsonElement): T
127
```
128
129
**Usage Examples:**
130
131
```kotlin
132
import kotlinx.serialization.json.*
133
134
@Serializable
135
data class Product(val id: Int, val name: String, val price: Double)
136
137
val product = Product(1, "Laptop", 999.99)
138
139
// Serialize to JsonElement
140
val jsonElement = Json.encodeToJsonElement(product)
141
142
// Manipulate JsonElement
143
val modifiedElement = buildJsonObject {
144
jsonElement.jsonObject.forEach { (key, value) ->
145
put(key, value)
146
}
147
put("category", "Electronics")
148
}
149
150
// Deserialize back to object
151
val modifiedProduct = Json.decodeFromJsonElement<Product>(modifiedElement)
152
```
153
154
### JSON Parsing
155
156
Parse JSON strings into JsonElement tree structures without requiring predefined data classes.
157
158
```kotlin { .api }
159
/**
160
* Parse a JSON string into a JsonElement tree
161
* @param string JSON string to parse
162
* @return JsonElement representing the parsed JSON
163
* @throws JsonDecodingException if the string is not valid JSON
164
*/
165
fun Json.parseToJsonElement(string: String): JsonElement
166
```
167
168
**Usage Examples:**
169
170
```kotlin
171
import kotlinx.serialization.json.*
172
173
// Parse JSON string to JsonElement
174
val jsonString = """
175
{
176
"users": [
177
{"name": "Alice", "active": true},
178
{"name": "Bob", "active": false}
179
],
180
"total": 2
181
}
182
"""
183
184
val jsonElement = Json.parseToJsonElement(jsonString)
185
186
// Navigate the JSON structure
187
val users = jsonElement.jsonObject["users"]?.jsonArray
188
val firstUser = users?.get(0)?.jsonObject
189
val userName = firstUser?.get("name")?.jsonPrimitive?.content
190
val isActive = firstUser?.get("active")?.jsonPrimitive?.boolean
191
192
val total = jsonElement.jsonObject["total"]?.jsonPrimitive?.int
193
```
194
195
### Polymorphic Serialization
196
197
Support for serializing and deserializing polymorphic class hierarchies.
198
199
```kotlin { .api }
200
/**
201
* Default class discriminator property name for polymorphic serialization
202
*/
203
val Json.classDiscriminator: String
204
205
/**
206
* Mode controlling when class discriminator is included
207
*/
208
val Json.classDiscriminatorMode: ClassDiscriminatorMode
209
210
enum class ClassDiscriminatorMode {
211
/** Never include class discriminator */
212
NONE,
213
/** Include discriminator for all JSON objects */
214
ALL_JSON_OBJECTS,
215
/** Include only for polymorphic classes (default) */
216
POLYMORPHIC
217
}
218
```
219
220
**Usage Examples:**
221
222
```kotlin
223
import kotlinx.serialization.*
224
import kotlinx.serialization.json.*
225
226
@Serializable
227
sealed class Animal {
228
abstract val name: String
229
}
230
231
@Serializable
232
@SerialName("dog")
233
data class Dog(override val name: String, val breed: String) : Animal()
234
235
@Serializable
236
@SerialName("cat")
237
data class Cat(override val name: String, val indoor: Boolean) : Animal()
238
239
// Configure Json for polymorphic serialization
240
val json = Json {
241
classDiscriminator = "type"
242
classDiscriminatorMode = ClassDiscriminatorMode.POLYMORPHIC
243
}
244
245
val animals = listOf<Animal>(
246
Dog("Buddy", "Golden Retriever"),
247
Cat("Whiskers", true)
248
)
249
250
val jsonString = json.encodeToString(animals)
251
// Result includes "type" discriminator field
252
253
val deserializedAnimals = json.decodeFromString<List<Animal>>(jsonString)
254
```
255
256
## Error Handling
257
258
The Json class throws standard kotlinx.serialization exceptions:
259
260
- **SerializationException**: Base exception for serialization errors
261
- **JsonDecodingException**: Malformed JSON input
262
- **IllegalArgumentException**: Invalid configuration or parameters
263
- **MissingFieldException**: Required field missing during deserialization
264
265
These exceptions provide detailed error messages indicating the location and nature of serialization problems.