0
# Core JSON Operations
1
2
Primary JSON serialization and deserialization functionality providing the essential methods for converting between Kotlin objects and JSON strings, with comprehensive configuration options.
3
4
## Capabilities
5
6
### Json Factory Functions
7
8
Create Json instances with custom configurations.
9
10
```kotlin { .api }
11
/**
12
* Creates a Json instance with default configuration
13
*/
14
fun Json(builderAction: JsonBuilder.() -> Unit = {}): Json
15
16
/**
17
* Creates a Json instance copying configuration from another Json instance
18
* @param from Base Json instance to copy configuration from
19
* @param builderAction Additional configuration changes
20
*/
21
fun Json(from: Json, builderAction: JsonBuilder.() -> Unit): Json
22
23
/**
24
* Default Json instance with standard configuration
25
*/
26
object Json {
27
companion object {
28
val Default: Json
29
}
30
}
31
```
32
33
**Usage Examples:**
34
35
```kotlin
36
// Default Json instance
37
val json = Json.Default
38
39
// Custom configuration
40
val customJson = Json {
41
ignoreUnknownKeys = true
42
prettyPrint = true
43
coerceInputValues = true
44
}
45
46
// Copy and modify existing configuration
47
val derivedJson = Json(customJson) {
48
encodeDefaults = true
49
}
50
```
51
52
### String Serialization
53
54
Encode Kotlin objects to JSON strings and decode JSON strings back to Kotlin objects.
55
56
```kotlin { .api }
57
/**
58
* Serializes the given value to a JSON string using the given serializer
59
* @param serializer Serialization strategy for type T
60
* @param value The value to serialize
61
* @return JSON string representation
62
*/
63
fun <T> Json.encodeToString(serializer: SerializationStrategy<T>, value: T): String
64
65
/**
66
* Serializes the given value to a JSON string using reified type serializer
67
* @param value The value to serialize
68
* @return JSON string representation
69
*/
70
inline fun <reified T> Json.encodeToString(value: T): String
71
72
/**
73
* Deserializes the given JSON string to a value using the given deserializer
74
* @param deserializer Deserialization strategy for type T
75
* @param string JSON string to deserialize
76
* @return Deserialized value
77
* @throws JsonDecodingException if string is malformed
78
*/
79
fun <T> Json.decodeFromString(deserializer: DeserializationStrategy<T>, string: String): T
80
81
/**
82
* Deserializes the given JSON string to a value using reified type deserializer
83
* @param string JSON string to deserialize
84
* @return Deserialized value
85
* @throws JsonDecodingException if string is malformed
86
*/
87
inline fun <reified T> Json.decodeFromString(string: String): T
88
```
89
90
**Usage Examples:**
91
92
```kotlin
93
@Serializable
94
data class Person(val name: String, val age: Int)
95
96
val json = Json { prettyPrint = true }
97
val person = Person("Alice", 30)
98
99
// Serialize with reified type
100
val jsonString = json.encodeToString(person)
101
// Result: {"name":"Alice","age":30}
102
103
// Serialize with explicit serializer
104
val jsonString2 = json.encodeToString(Person.serializer(), person)
105
106
// Deserialize with reified type
107
val parsed = json.decodeFromString<Person>(jsonString)
108
109
// Deserialize with explicit deserializer
110
val parsed2 = json.decodeFromString(Person.serializer(), jsonString)
111
```
112
113
### JsonElement Serialization
114
115
Convert between Kotlin objects and JsonElement tree representations for programmatic JSON manipulation.
116
117
```kotlin { .api }
118
/**
119
* Serializes the given value to a JsonElement using the given serializer
120
* @param serializer Serialization strategy for type T
121
* @param value The value to serialize
122
* @return JsonElement representation
123
*/
124
fun <T> Json.encodeToJsonElement(serializer: SerializationStrategy<T>, value: T): JsonElement
125
126
/**
127
* Serializes the given value to a JsonElement using reified type serializer
128
* @param value The value to serialize
129
* @return JsonElement representation
130
*/
131
inline fun <reified T> Json.encodeToJsonElement(value: T): JsonElement
132
133
/**
134
* Deserializes the given JsonElement to a value using the given deserializer
135
* @param deserializer Deserialization strategy for type T
136
* @param element JsonElement to deserialize
137
* @return Deserialized value
138
* @throws JsonDecodingException if element structure is invalid
139
*/
140
fun <T> Json.decodeFromJsonElement(deserializer: DeserializationStrategy<T>, element: JsonElement): T
141
142
/**
143
* Deserializes the given JsonElement to a value using reified type deserializer
144
* @param element JsonElement to deserialize
145
* @return Deserialized value
146
* @throws JsonDecodingException if element structure is invalid
147
*/
148
inline fun <reified T> Json.decodeFromJsonElement(element: JsonElement): T
149
150
/**
151
* Parses the given JSON string to a JsonElement
152
* @param string JSON string to parse
153
* @return JsonElement tree representation
154
* @throws JsonDecodingException if string is malformed
155
*/
156
fun Json.parseToJsonElement(string: String): JsonElement
157
```
158
159
**Usage Examples:**
160
161
```kotlin
162
@Serializable
163
data class Config(val host: String, val port: Int, val ssl: Boolean)
164
165
val json = Json.Default
166
val config = Config("localhost", 8080, true)
167
168
// Serialize to JsonElement
169
val element = json.encodeToJsonElement(config)
170
// element is JsonObject containing the data
171
172
// Access JsonElement programmatically
173
val jsonObject = element.jsonObject
174
val host = jsonObject["host"]?.jsonPrimitive?.content
175
val port = jsonObject["port"]?.jsonPrimitive?.int
176
177
// Deserialize from JsonElement
178
val parsedConfig = json.decodeFromJsonElement<Config>(element)
179
180
// Parse string to JsonElement
181
val jsonString = """{"host":"server.com","port":443,"ssl":true}"""
182
val parsedElement = json.parseToJsonElement(jsonString)
183
val configFromParsed = json.decodeFromJsonElement<Config>(parsedElement)
184
```
185
186
### Error Handling
187
188
JSON operations can throw specific exceptions for different types of errors.
189
190
```kotlin { .api }
191
/**
192
* Exception thrown during JSON encoding
193
*/
194
class JsonEncodingException(message: String) : SerializationException(message)
195
196
/**
197
* Exception thrown during JSON decoding
198
*/
199
class JsonDecodingException(message: String) : SerializationException(message)
200
```
201
202
**Error Handling Examples:**
203
204
```kotlin
205
try {
206
val result = json.decodeFromString<Person>("""{"name":"John"}""") // missing "age"
207
} catch (e: JsonDecodingException) {
208
println("Failed to decode: ${e.message}")
209
}
210
211
try {
212
val malformedJson = """{"name":"John", "age":}""" // invalid syntax
213
val result = json.parseToJsonElement(malformedJson)
214
} catch (e: JsonDecodingException) {
215
println("Malformed JSON: ${e.message}")
216
}
217
```
218
219
## Common Patterns
220
221
### Working with Nullable Values
222
223
```kotlin
224
@Serializable
225
data class User(val name: String, val email: String?)
226
227
val json = Json {
228
explicitNulls = false // Don't include null values in output
229
}
230
231
val user = User("Bob", null)
232
val jsonString = json.encodeToString(user)
233
// Result: {"name":"Bob"} (email omitted)
234
```
235
236
### Handling Unknown Properties
237
238
```kotlin
239
val json = Json {
240
ignoreUnknownKeys = true // Ignore extra properties during deserialization
241
}
242
243
val jsonWithExtra = """{"name":"Alice","age":25,"country":"US"}"""
244
val person = json.decodeFromString<Person>(jsonWithExtra) // Works despite extra "country"
245
```
246
247
### Pretty Printing
248
249
```kotlin
250
val json = Json {
251
prettyPrint = true
252
prettyPrintIndent = " " // Use 2 spaces for indentation
253
}
254
255
val formatted = json.encodeToString(person)
256
// Result:
257
// {
258
// "name": "Alice",
259
// "age": 25
260
// }
261
```