A Kotlin multiplatform library for JSON serialization providing type-safe JSON parsing and object serialization
—
JSON Document Object Model providing type-safe programmatic access to JSON structures without requiring predefined data classes. The JsonElement hierarchy enables dynamic JSON manipulation, validation, and transformation.
Base sealed class for all JSON elements, enabling pattern matching and type-safe casting.
/**
* Base class for all JSON elements
* Represents any valid JSON value: object, array, primitive, or null
*/
@Serializable(JsonElementSerializer::class)
sealed class JsonElementRepresents JSON primitive values: strings, numbers, booleans, and null.
/**
* Represents JSON primitive values (strings, numbers, booleans)
*/
@Serializable(JsonPrimitiveSerializer::class)
sealed class JsonPrimitive : JsonElement {
/** Whether this primitive should be serialized as a quoted string */
val isString: Boolean
/** Raw content of the primitive without quotes */
val content: String
}
/**
* Represents JSON null value
*/
@Serializable(JsonNullSerializer::class)
object JsonNull : JsonPrimitive {
override val isString: Boolean = false
override val content: String = "null"
}Represents JSON objects as key-value maps.
/**
* Represents JSON objects as key-value pairs
* Implements Map<String, JsonElement> for convenient access
*/
@Serializable(JsonObjectSerializer::class)
class JsonObject(content: Map<String, JsonElement>) : JsonElement, Map<String, JsonElement>Usage Examples:
import kotlinx.serialization.json.*
// Access object properties
val json = Json.parseToJsonElement("""{"name": "Alice", "age": 30}""")
val jsonObject = json.jsonObject
val name = jsonObject["name"]?.jsonPrimitive?.content // "Alice"
val age = jsonObject["age"]?.jsonPrimitive?.int // 30
// Iterate over properties
jsonObject.forEach { (key, value) ->
println("$key: $value")
}
// Check if key exists
if ("email" in jsonObject) {
val email = jsonObject["email"]?.jsonPrimitive?.content
}Represents JSON arrays as ordered lists.
/**
* Represents JSON arrays as ordered lists of elements
* Implements List<JsonElement> for convenient access
*/
@Serializable(JsonArraySerializer::class)
class JsonArray(content: List<JsonElement>) : JsonElement, List<JsonElement>Usage Examples:
import kotlinx.serialization.json.*
// Access array elements
val json = Json.parseToJsonElement("""[1, "hello", true, null]""")
val jsonArray = json.jsonArray
val firstNumber = jsonArray[0].jsonPrimitive.int // 1
val secondString = jsonArray[1].jsonPrimitive.content // "hello"
val thirdBoolean = jsonArray[2].jsonPrimitive.boolean // true
val fourthNull = jsonArray[3] // JsonNull
// Iterate over elements
jsonArray.forEachIndexed { index, element ->
println("Element $index: $element")
}
// Array operations
val size = jsonArray.size
val isEmpty = jsonArray.isEmpty()Factory functions for creating JsonPrimitive instances from various Kotlin types.
/**
* Create JsonPrimitive from Boolean value
*/
fun JsonPrimitive(value: Boolean?): JsonPrimitive
/**
* Create JsonPrimitive from Number value
*/
fun JsonPrimitive(value: Number?): JsonPrimitive
/**
* Create JsonPrimitive from String value
*/
fun JsonPrimitive(value: String?): JsonPrimitive
/**
* Create JsonPrimitive from unsigned byte value
*/
@ExperimentalSerializationApi
fun JsonPrimitive(value: UByte): JsonPrimitive
/**
* Create JsonPrimitive from unsigned short value
*/
@ExperimentalSerializationApi
fun JsonPrimitive(value: UShort): JsonPrimitive
/**
* Create JsonPrimitive from unsigned int value
*/
@ExperimentalSerializationApi
fun JsonPrimitive(value: UInt): JsonPrimitive
/**
* Create JsonPrimitive from unsigned long value
*/
@ExperimentalSerializationApi
fun JsonPrimitive(value: ULong): JsonPrimitive
/**
* Create JsonNull from Nothing? (always null)
*/
@ExperimentalSerializationApi
fun JsonPrimitive(value: Nothing?): JsonNull
/**
* Create unquoted literal JsonPrimitive (for raw JSON values)
*/
@ExperimentalSerializationApi
fun JsonUnquotedLiteral(value: String?): JsonPrimitiveUsage Examples:
import kotlinx.serialization.json.*
// Create primitives from various types
val stringPrimitive = JsonPrimitive("Hello World")
val numberPrimitive = JsonPrimitive(42)
val booleanPrimitive = JsonPrimitive(true)
val nullPrimitive = JsonPrimitive(null as String?) // Creates JsonNull
// Create unquoted literals (experimental)
val rawJson = JsonUnquotedLiteral("true") // Creates unquoted booleanExtension properties for safe casting between JsonElement types.
/**
* Cast JsonElement to JsonPrimitive
* @throws IllegalArgumentException if element is not a JsonPrimitive
*/
val JsonElement.jsonPrimitive: JsonPrimitive
/**
* Cast JsonElement to JsonObject
* @throws IllegalArgumentException if element is not a JsonObject
*/
val JsonElement.jsonObject: JsonObject
/**
* Cast JsonElement to JsonArray
* @throws IllegalArgumentException if element is not a JsonArray
*/
val JsonElement.jsonArray: JsonArray
/**
* Cast JsonElement to JsonNull
* @throws IllegalArgumentException if element is not JsonNull
*/
val JsonElement.jsonNull: JsonNullExtension properties for extracting typed values from JsonPrimitive.
/**
* Extract Int value from JsonPrimitive
* @throws IllegalArgumentException if primitive cannot be converted to Int
*/
val JsonPrimitive.int: Int
/**
* Extract Int value from JsonPrimitive, returning null if conversion fails
*/
val JsonPrimitive.intOrNull: Int?
/**
* Extract Long value from JsonPrimitive
* @throws IllegalArgumentException if primitive cannot be converted to Long
*/
val JsonPrimitive.long: Long
/**
* Extract Long value from JsonPrimitive, returning null if conversion fails
*/
val JsonPrimitive.longOrNull: Long?
/**
* Extract Double value from JsonPrimitive
* @throws IllegalArgumentException if primitive cannot be converted to Double
*/
val JsonPrimitive.double: Double
/**
* Extract Double value from JsonPrimitive, returning null if conversion fails
*/
val JsonPrimitive.doubleOrNull: Double?
/**
* Extract Float value from JsonPrimitive
* @throws IllegalArgumentException if primitive cannot be converted to Float
*/
val JsonPrimitive.float: Float
/**
* Extract Float value from JsonPrimitive, returning null if conversion fails
*/
val JsonPrimitive.floatOrNull: Float?
/**
* Extract Boolean value from JsonPrimitive
* @throws IllegalArgumentException if primitive cannot be converted to Boolean
*/
val JsonPrimitive.boolean: Boolean
/**
* Extract Boolean value from JsonPrimitive, returning null if conversion fails
*/
val JsonPrimitive.booleanOrNull: Boolean?
/**
* Extract String content from JsonPrimitive, returning null if JsonNull
*/
val JsonPrimitive.contentOrNull: String?Usage Examples:
import kotlinx.serialization.json.*
val json = Json.parseToJsonElement("""
{
"name": "Alice",
"age": 30,
"height": 5.6,
"active": true,
"scores": [95, 87, 92],
"address": null
}
""")
val obj = json.jsonObject
// Safe casting and value extraction
val name = obj["name"]?.jsonPrimitive?.content // "Alice"
val age = obj["age"]?.jsonPrimitive?.int // 30
val height = obj["height"]?.jsonPrimitive?.double // 5.6
val active = obj["active"]?.jsonPrimitive?.boolean // true
// Handle nullable values
val address = obj["address"]?.jsonPrimitive?.contentOrNull // null
// Array access
val scores = obj["scores"]?.jsonArray
val firstScore = scores?.get(0)?.jsonPrimitive?.int // 95
// Safe extraction with null handling
val maybeAge = obj["age"]?.jsonPrimitive?.intOrNull // 30
val invalidAge = obj["name"]?.jsonPrimitive?.intOrNull // null (can't convert "Alice" to int)JsonElement's sealed class design enables exhaustive pattern matching.
import kotlinx.serialization.json.*
fun processJsonElement(element: JsonElement): String = when (element) {
is JsonObject -> "Object with ${element.size} properties"
is JsonArray -> "Array with ${element.size} elements"
is JsonPrimitive -> when {
element.isString -> "String: ${element.content}"
element == JsonNull -> "Null value"
element.booleanOrNull != null -> "Boolean: ${element.boolean}"
element.intOrNull != null -> "Integer: ${element.int}"
element.doubleOrNull != null -> "Number: ${element.double}"
else -> "Other primitive: ${element.content}"
}
}import kotlinx.serialization.json.*
val json = Json.parseToJsonElement("""
{
"users": [
{
"profile": {
"name": "Alice",
"preferences": {
"theme": "dark"
}
}
}
]
}
""")
// Navigate deeply nested structure
val theme = json.jsonObject["users"]
?.jsonArray?.get(0)
?.jsonObject?.get("profile")
?.jsonObject?.get("preferences")
?.jsonObject?.get("theme")
?.jsonPrimitive?.content // "dark"import kotlinx.serialization.json.*
fun validateUserJson(element: JsonElement): Boolean {
if (element !is JsonObject) return false
val name = element["name"]?.jsonPrimitive?.contentOrNull
val age = element["age"]?.jsonPrimitive?.intOrNull
val email = element["email"]?.jsonPrimitive?.contentOrNull
return name != null &&
age != null && age >= 0 &&
email != null && email.contains("@")
}JsonElement operations can throw exceptions:
jsonObject on JsonArray)int on non-numeric string)getValue())Use the null-safe extraction properties (intOrNull, booleanOrNull, etc.) to avoid exceptions when the conversion might fail.
Install with Tessl CLI
npx tessl i tessl/maven-org-jetbrains-kotlinx--kotlinx-serialization-json-jvm