Kotlin multiplatform JSON serialization library with type-safe, reflectionless approach supporting all platforms
—
Core serialization and deserialization functionality for converting between Kotlin objects and JSON strings or JsonElement representations.
The main entry point for JSON serialization providing configurable encoding and decoding operations.
/**
* Main entry point for JSON serialization with configurable behavior
*/
sealed class Json(
val configuration: JsonConfiguration,
override val serializersModule: SerializersModule
) : StringFormat {
companion object Default : Json
}Convert Kotlin objects to and from JSON strings.
/**
* Serializes the value into JSON string using the given serializer
* @param serializer Strategy for serializing type T
* @param value Value to serialize
* @return JSON string representation
* @throws SerializationException if value cannot be serialized
*/
fun <T> Json.encodeToString(serializer: SerializationStrategy<T>, value: T): String
/**
* Serializes the value using serializer retrieved from reified type parameter
* @param value Value to serialize
* @return JSON string representation
* @throws SerializationException if value cannot be serialized
*/
inline fun <reified T> Json.encodeToString(value: T): String
/**
* Deserializes JSON string to value of type T using the given deserializer
* @param deserializer Strategy for deserializing type T
* @param string JSON string to deserialize
* @return Deserialized value of type T
* @throws SerializationException if JSON is invalid for type T
* @throws IllegalArgumentException if decoded input is invalid for type T
*/
fun <T> Json.decodeFromString(deserializer: DeserializationStrategy<T>, string: String): T
/**
* Deserializes JSON string using deserializer retrieved from reified type parameter
* @param string JSON string to deserialize
* @return Deserialized value of type T
* @throws SerializationException if JSON is invalid for type T
* @throws IllegalArgumentException if decoded input is invalid for type T
*/
inline fun <reified T> Json.decodeFromString(string: String): TUsage Examples:
import kotlinx.serialization.*
import kotlinx.serialization.json.*
@Serializable
data class Person(val name: String, val age: Int)
// String serialization
val person = Person("Alice", 30)
val jsonString = Json.encodeToString(person)
// Result: {"name":"Alice","age":30}
// String deserialization
val personFromJson = Json.decodeFromString<Person>(jsonString)
// With explicit serializer
val jsonWithSerializer = Json.encodeToString(Person.serializer(), person)
val personWithSerializer = Json.decodeFromString(Person.serializer(), jsonString)Convert Kotlin objects to and from JsonElement for programmatic JSON manipulation.
/**
* Serializes the value into JsonElement using the given serializer
* @param serializer Strategy for serializing type T
* @param value Value to serialize
* @return JsonElement representation
* @throws SerializationException if value cannot be serialized
*/
fun <T> Json.encodeToJsonElement(serializer: SerializationStrategy<T>, value: T): JsonElement
/**
* Serializes the value using serializer retrieved from reified type parameter
* @param value Value to serialize
* @return JsonElement representation
* @throws SerializationException if value cannot be serialized
*/
inline fun <reified T> Json.encodeToJsonElement(value: T): JsonElement
/**
* Deserializes JsonElement to value of type T using the given deserializer
* @param deserializer Strategy for deserializing type T
* @param element JsonElement to deserialize
* @return Deserialized value of type T
* @throws SerializationException if element is invalid for type T
* @throws IllegalArgumentException if decoded input is invalid for type T
*/
fun <T> Json.decodeFromJsonElement(deserializer: DeserializationStrategy<T>, element: JsonElement): T
/**
* Deserializes JsonElement using deserializer retrieved from reified type parameter
* @param json JsonElement to deserialize
* @return Deserialized value of type T
* @throws SerializationException if element is invalid for type T
* @throws IllegalArgumentException if decoded input is invalid for type T
*/
inline fun <reified T> Json.decodeFromJsonElement(json: JsonElement): TUsage Examples:
@Serializable
data class Config(val timeout: Int, val retries: Int)
val config = Config(timeout = 5000, retries = 3)
// Encode to JsonElement
val element = Json.encodeToJsonElement(config)
// element is JsonObject with structure
// Decode from JsonElement
val configFromElement = Json.decodeFromJsonElement<Config>(element)
// Manual JsonElement creation
val manualElement = buildJsonObject {
put("timeout", 10000)
put("retries", 5)
}
val configFromManual = Json.decodeFromJsonElement<Config>(manualElement)Parse JSON strings into JsonElement for inspection and manipulation.
/**
* Deserializes JSON string into corresponding JsonElement representation
* @param string JSON string to parse
* @return JsonElement representation of the JSON
* @throws SerializationException if string is not valid JSON
*/
fun Json.parseToJsonElement(string: String): JsonElementUsage Examples:
// Parse JSON string to element
val jsonString = """{"users":[{"name":"Alice","active":true},{"name":"Bob","active":false}]}"""
val element = Json.parseToJsonElement(jsonString)
// Navigate the element structure
val usersArray = element.jsonObject["users"]?.jsonArray
val firstUser = usersArray?.get(0)?.jsonObject
val firstName = firstUser?.get("name")?.jsonPrimitive?.content
// firstName = "Alice"
// Check user status
val isActive = firstUser?.get("active")?.jsonPrimitive?.boolean
// isActive = trueCreate configured Json instances with custom behavior.
/**
* Creates Json instance configured from optionally given Json instance and adjusted with builderAction
* @param from Base Json instance to inherit configuration from (defaults to Json.Default)
* @param builderAction Configuration block for customizing Json behavior
* @return Configured Json instance
*/
fun Json(from: Json = Json.Default, builderAction: JsonBuilder.() -> Unit): JsonUsage Examples:
// Create custom Json instance
val prettyJson = Json {
prettyPrint = true
ignoreUnknownKeys = true
encodeDefaults = false
}
// Inherit from existing configuration
val productionJson = Json(prettyJson) {
prettyPrint = false // Override for production
coerceInputValues = true
}
@Serializable
data class ApiResponse(val status: String, val data: String? = null)
val response = ApiResponse("success", "Hello World")
val formatted = prettyJson.encodeToString(response)
/*
{
"status": "success",
"data": "Hello World"
}
*/Install with Tessl CLI
npx tessl i tessl/maven-org-jetbrains-kotlinx--kotlinx-serialization-json