0
# JsonElement Hierarchy
1
2
Abstract representation of JSON data structures providing a DOM-like API for working with JSON without specific types.
3
4
## Capabilities
5
6
### JsonElement Base Class
7
8
Base sealed class representing any JSON value.
9
10
```kotlin { .api }
11
/**
12
* Base class representing single JSON element
13
* Can be JsonPrimitive, JsonArray, or JsonObject
14
*/
15
sealed class JsonElement
16
```
17
18
### JsonPrimitive
19
20
Base class for JSON primitive values including strings, numbers, booleans, and null.
21
22
```kotlin { .api }
23
/**
24
* Base class representing JSON primitive value
25
* JSON primitives include numbers, strings, booleans and special null value
26
*/
27
sealed class JsonPrimitive : JsonElement() {
28
/**
29
* Indicates whether the primitive was explicitly constructed from String
30
* and whether it should be serialized as one
31
*/
32
abstract val isString: Boolean
33
34
/**
35
* Content of given element without quotes
36
* For JsonNull, returns "null" string
37
*/
38
abstract val content: String
39
}
40
```
41
42
### JsonNull
43
44
Singleton object representing JSON null value.
45
46
```kotlin { .api }
47
/**
48
* Represents JSON null value
49
*/
50
object JsonNull : JsonPrimitive() {
51
override val isString: Boolean // Always false
52
override val content: String // Always "null"
53
}
54
```
55
56
### JsonObject
57
58
Represents JSON object implementing Map interface for convenient access.
59
60
```kotlin { .api }
61
/**
62
* Represents JSON object, consisting of name-value pairs
63
* Also implements Map interface for traditional access methods
64
*/
65
class JsonObject(
66
private val content: Map<String, JsonElement>
67
) : JsonElement(), Map<String, JsonElement> by content
68
```
69
70
**Usage Examples:**
71
72
```kotlin
73
// Create JsonObject
74
val jsonObj = JsonObject(mapOf(
75
"name" to JsonPrimitive("Alice"),
76
"age" to JsonPrimitive(25),
77
"active" to JsonPrimitive(true)
78
))
79
80
// Access using Map interface
81
val name = jsonObj["name"]?.jsonPrimitive?.content // "Alice"
82
val age = jsonObj["age"]?.jsonPrimitive?.int // 25
83
val active = jsonObj["active"]?.jsonPrimitive?.boolean // true
84
85
// Iterate over entries
86
for ((key, value) in jsonObj) {
87
println("$key: $value")
88
}
89
```
90
91
### JsonArray
92
93
Represents JSON array implementing List interface for convenient access.
94
95
```kotlin { .api }
96
/**
97
* Represents JSON array, consisting of indexed values
98
* Also implements List interface for traditional access methods
99
*/
100
class JsonArray(private val content: List<JsonElement>) : JsonElement(), List<JsonElement> by content
101
```
102
103
**Usage Examples:**
104
105
```kotlin
106
// Create JsonArray
107
val jsonArr = JsonArray(listOf(
108
JsonPrimitive("Alice"),
109
JsonPrimitive("Bob"),
110
JsonPrimitive("Charlie")
111
))
112
113
// Access using List interface
114
val first = jsonArr[0].jsonPrimitive.content // "Alice"
115
val size = jsonArr.size // 3
116
117
// Iterate over elements
118
for (element in jsonArr) {
119
println(element.jsonPrimitive.content)
120
}
121
122
// Convert to regular list
123
val names = jsonArr.map { it.jsonPrimitive.content }
124
```
125
126
### JsonPrimitive Factory Functions
127
128
Factory functions for creating JsonPrimitive instances from various types.
129
130
```kotlin { .api }
131
/** Creates JsonPrimitive from boolean value, null creates JsonNull */
132
fun JsonPrimitive(value: Boolean?): JsonPrimitive
133
134
/** Creates JsonPrimitive from numeric value, null creates JsonNull */
135
fun JsonPrimitive(value: Number?): JsonPrimitive
136
137
/** Creates JsonPrimitive from string value, null creates JsonNull */
138
fun JsonPrimitive(value: String?): JsonPrimitive
139
140
/** Creates numeric JsonPrimitive from UByte */
141
fun JsonPrimitive(value: UByte): JsonPrimitive
142
143
/** Creates numeric JsonPrimitive from UShort */
144
fun JsonPrimitive(value: UShort): JsonPrimitive
145
146
/** Creates numeric JsonPrimitive from UInt */
147
fun JsonPrimitive(value: UInt): JsonPrimitive
148
149
/** Creates numeric JsonPrimitive from ULong */
150
fun JsonPrimitive(value: ULong): JsonPrimitive
151
152
/** Creates JsonNull from null literal */
153
fun JsonPrimitive(value: Nothing?): JsonNull
154
155
/**
156
* Creates JsonPrimitive from string without surrounding it in quotes
157
* Used for raw JSON values like precise numbers or complex objects
158
* @param value String content to use as unquoted literal
159
* @throws JsonEncodingException if value equals "null"
160
*/
161
fun JsonUnquotedLiteral(value: String?): JsonPrimitive
162
```
163
164
**Usage Examples:**
165
166
```kotlin
167
// Primitive creation
168
val stringPrim = JsonPrimitive("Hello") // Quoted string
169
val numberPrim = JsonPrimitive(42) // Number
170
val boolPrim = JsonPrimitive(true) // Boolean
171
val nullPrim = JsonPrimitive(null) // JsonNull
172
173
// Unsigned integers
174
val ubytePrim = JsonPrimitive(255u) // UByte as number
175
val ulongPrim = JsonPrimitive(123456789UL) // ULong as number
176
177
// Unquoted literals for special cases
178
val precisePrim = JsonUnquotedLiteral("123.456789012345") // Precise number
179
val rawJsonPrim = JsonUnquotedLiteral("""{"nested": true}""") // Raw JSON
180
```
181
182
### JsonElement Extension Properties
183
184
Convenience extension properties for casting JsonElement to specific types.
185
186
```kotlin { .api }
187
/** Convenience method to get current element as JsonPrimitive */
188
val JsonElement.jsonPrimitive: JsonPrimitive
189
190
/** Convenience method to get current element as JsonObject */
191
val JsonElement.jsonObject: JsonObject
192
193
/** Convenience method to get current element as JsonArray */
194
val JsonElement.jsonArray: JsonArray
195
196
/** Convenience method to get current element as JsonNull */
197
val JsonElement.jsonNull: JsonNull
198
```
199
200
### JsonPrimitive Extension Properties
201
202
Extension properties for extracting typed values from JsonPrimitive.
203
204
```kotlin { .api }
205
/** Returns content as int, throws NumberFormatException if invalid */
206
val JsonPrimitive.int: Int
207
208
/** Returns content as int or null if invalid */
209
val JsonPrimitive.intOrNull: Int?
210
211
/** Returns content as long, throws NumberFormatException if invalid */
212
val JsonPrimitive.long: Long
213
214
/** Returns content as long or null if invalid */
215
val JsonPrimitive.longOrNull: Long?
216
217
/** Returns content as double, throws NumberFormatException if invalid */
218
val JsonPrimitive.double: Double
219
220
/** Returns content as double or null if invalid */
221
val JsonPrimitive.doubleOrNull: Double?
222
223
/** Returns content as float, throws NumberFormatException if invalid */
224
val JsonPrimitive.float: Float
225
226
/** Returns content as float or null if invalid */
227
val JsonPrimitive.floatOrNull: Float?
228
229
/** Returns content as boolean, throws IllegalStateException if invalid */
230
val JsonPrimitive.boolean: Boolean
231
232
/** Returns content as boolean or null if invalid */
233
val JsonPrimitive.booleanOrNull: Boolean?
234
235
/** Content without quotes or null if JsonNull */
236
val JsonPrimitive.contentOrNull: String?
237
```
238
239
**Usage Examples:**
240
241
```kotlin
242
// Type-safe extraction
243
val jsonStr = """{"count": 42, "active": true, "name": "test", "value": null}"""
244
val element = Json.parseToJsonElement(jsonStr)
245
val obj = element.jsonObject
246
247
// Extract typed values
248
val count = obj["count"]?.jsonPrimitive?.int // 42
249
val active = obj["active"]?.jsonPrimitive?.boolean // true
250
val name = obj["name"]?.jsonPrimitive?.content // "test"
251
val value = obj["value"]?.jsonPrimitive?.contentOrNull // null
252
253
// Safe extraction with null handling
254
val maybeCount = obj["count"]?.jsonPrimitive?.intOrNull // 42
255
val maybeBoolean = obj["active"]?.jsonPrimitive?.booleanOrNull // true
256
val invalidInt = obj["name"]?.jsonPrimitive?.intOrNull // null (can't parse "test" as int)
257
258
// Working with arrays
259
val arrayJson = """[1, 2.5, "text", true, null]"""
260
val array = Json.parseToJsonElement(arrayJson).jsonArray
261
262
val intVal = array[0].jsonPrimitive.int // 1
263
val doubleVal = array[1].jsonPrimitive.double // 2.5
264
val strVal = array[2].jsonPrimitive.content // "text"
265
val boolVal = array[3].jsonPrimitive.boolean // true
266
val nullVal = array[4].jsonPrimitive.contentOrNull // null
267
```