0
# Core JSON Operations
1
2
Core serialization and deserialization functionality for converting between Kotlin objects and JSON strings or JsonElement representations.
3
4
## Capabilities
5
6
### Json Class
7
8
The main entry point for JSON serialization providing configurable encoding and decoding operations.
9
10
```kotlin { .api }
11
/**
12
* Main entry point for JSON serialization with configurable behavior
13
*/
14
sealed class Json(
15
val configuration: JsonConfiguration,
16
override val serializersModule: SerializersModule
17
) : StringFormat {
18
companion object Default : Json
19
}
20
```
21
22
### String Serialization
23
24
Convert Kotlin objects to and from JSON strings.
25
26
```kotlin { .api }
27
/**
28
* Serializes the value into JSON string using the given serializer
29
* @param serializer Strategy for serializing type T
30
* @param value Value to serialize
31
* @return JSON string representation
32
* @throws SerializationException if value cannot be serialized
33
*/
34
fun <T> Json.encodeToString(serializer: SerializationStrategy<T>, value: T): String
35
36
/**
37
* Serializes the value using serializer retrieved from reified type parameter
38
* @param value Value to serialize
39
* @return JSON string representation
40
* @throws SerializationException if value cannot be serialized
41
*/
42
inline fun <reified T> Json.encodeToString(value: T): String
43
44
/**
45
* Deserializes JSON string to value of type T using the given deserializer
46
* @param deserializer Strategy for deserializing type T
47
* @param string JSON string to deserialize
48
* @return Deserialized value of type T
49
* @throws SerializationException if JSON is invalid for type T
50
* @throws IllegalArgumentException if decoded input is invalid for type T
51
*/
52
fun <T> Json.decodeFromString(deserializer: DeserializationStrategy<T>, string: String): T
53
54
/**
55
* Deserializes JSON string using deserializer retrieved from reified type parameter
56
* @param string JSON string to deserialize
57
* @return Deserialized value of type T
58
* @throws SerializationException if JSON is invalid for type T
59
* @throws IllegalArgumentException if decoded input is invalid for type T
60
*/
61
inline fun <reified T> Json.decodeFromString(string: String): T
62
```
63
64
**Usage Examples:**
65
66
```kotlin
67
import kotlinx.serialization.*
68
import kotlinx.serialization.json.*
69
70
@Serializable
71
data class Person(val name: String, val age: Int)
72
73
// String serialization
74
val person = Person("Alice", 30)
75
val jsonString = Json.encodeToString(person)
76
// Result: {"name":"Alice","age":30}
77
78
// String deserialization
79
val personFromJson = Json.decodeFromString<Person>(jsonString)
80
81
// With explicit serializer
82
val jsonWithSerializer = Json.encodeToString(Person.serializer(), person)
83
val personWithSerializer = Json.decodeFromString(Person.serializer(), jsonString)
84
```
85
86
### JsonElement Serialization
87
88
Convert Kotlin objects to and from JsonElement for programmatic JSON manipulation.
89
90
```kotlin { .api }
91
/**
92
* Serializes the value into JsonElement using the given serializer
93
* @param serializer Strategy for serializing type T
94
* @param value Value to serialize
95
* @return JsonElement representation
96
* @throws SerializationException if value cannot be serialized
97
*/
98
fun <T> Json.encodeToJsonElement(serializer: SerializationStrategy<T>, value: T): JsonElement
99
100
/**
101
* Serializes the value using serializer retrieved from reified type parameter
102
* @param value Value to serialize
103
* @return JsonElement representation
104
* @throws SerializationException if value cannot be serialized
105
*/
106
inline fun <reified T> Json.encodeToJsonElement(value: T): JsonElement
107
108
/**
109
* Deserializes JsonElement to value of type T using the given deserializer
110
* @param deserializer Strategy for deserializing type T
111
* @param element JsonElement to deserialize
112
* @return Deserialized value of type T
113
* @throws SerializationException if element is invalid for type T
114
* @throws IllegalArgumentException if decoded input is invalid for type T
115
*/
116
fun <T> Json.decodeFromJsonElement(deserializer: DeserializationStrategy<T>, element: JsonElement): T
117
118
/**
119
* Deserializes JsonElement using deserializer retrieved from reified type parameter
120
* @param json JsonElement to deserialize
121
* @return Deserialized value of type T
122
* @throws SerializationException if element is invalid for type T
123
* @throws IllegalArgumentException if decoded input is invalid for type T
124
*/
125
inline fun <reified T> Json.decodeFromJsonElement(json: JsonElement): T
126
```
127
128
**Usage Examples:**
129
130
```kotlin
131
@Serializable
132
data class Config(val timeout: Int, val retries: Int)
133
134
val config = Config(timeout = 5000, retries = 3)
135
136
// Encode to JsonElement
137
val element = Json.encodeToJsonElement(config)
138
// element is JsonObject with structure
139
140
// Decode from JsonElement
141
val configFromElement = Json.decodeFromJsonElement<Config>(element)
142
143
// Manual JsonElement creation
144
val manualElement = buildJsonObject {
145
put("timeout", 10000)
146
put("retries", 5)
147
}
148
val configFromManual = Json.decodeFromJsonElement<Config>(manualElement)
149
```
150
151
### JSON Parsing
152
153
Parse JSON strings into JsonElement for inspection and manipulation.
154
155
```kotlin { .api }
156
/**
157
* Deserializes JSON string into corresponding JsonElement representation
158
* @param string JSON string to parse
159
* @return JsonElement representation of the JSON
160
* @throws SerializationException if string is not valid JSON
161
*/
162
fun Json.parseToJsonElement(string: String): JsonElement
163
```
164
165
**Usage Examples:**
166
167
```kotlin
168
// Parse JSON string to element
169
val jsonString = """{"users":[{"name":"Alice","active":true},{"name":"Bob","active":false}]}"""
170
val element = Json.parseToJsonElement(jsonString)
171
172
// Navigate the element structure
173
val usersArray = element.jsonObject["users"]?.jsonArray
174
val firstUser = usersArray?.get(0)?.jsonObject
175
val firstName = firstUser?.get("name")?.jsonPrimitive?.content
176
// firstName = "Alice"
177
178
// Check user status
179
val isActive = firstUser?.get("active")?.jsonPrimitive?.boolean
180
// isActive = true
181
```
182
183
### Json Factory Function
184
185
Create configured Json instances with custom behavior.
186
187
```kotlin { .api }
188
/**
189
* Creates Json instance configured from optionally given Json instance and adjusted with builderAction
190
* @param from Base Json instance to inherit configuration from (defaults to Json.Default)
191
* @param builderAction Configuration block for customizing Json behavior
192
* @return Configured Json instance
193
*/
194
fun Json(from: Json = Json.Default, builderAction: JsonBuilder.() -> Unit): Json
195
```
196
197
**Usage Examples:**
198
199
```kotlin
200
// Create custom Json instance
201
val prettyJson = Json {
202
prettyPrint = true
203
ignoreUnknownKeys = true
204
encodeDefaults = false
205
}
206
207
// Inherit from existing configuration
208
val productionJson = Json(prettyJson) {
209
prettyPrint = false // Override for production
210
coerceInputValues = true
211
}
212
213
@Serializable
214
data class ApiResponse(val status: String, val data: String? = null)
215
216
val response = ApiResponse("success", "Hello World")
217
val formatted = prettyJson.encodeToString(response)
218
/*
219
{
220
"status": "success",
221
"data": "Hello World"
222
}
223
*/
224
```