CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-jetbrains-kotlinx--kotlinx-serialization-json-jvm

A Kotlin multiplatform library for JSON serialization providing type-safe JSON parsing and object serialization

Pending
Overview
Eval results
Files

serialization.mddocs/

Core Serialization

Core JSON serialization and deserialization functionality providing high-level APIs for converting between Kotlin objects and JSON strings or JsonElements.

Capabilities

Json Object

The main entry point for JSON operations, providing both instance methods and a default singleton.

/**
 * Main class for JSON serialization and deserialization operations
 */
sealed class Json : StringFormat {
    val configuration: JsonConfiguration
    val serializersModule: SerializersModule
    
    companion object {
        val Default: Json
    }
}

/**
 * Create a Json instance with custom configuration
 * @param from Base Json instance to inherit settings from (defaults to Json.Default)
 * @param builderAction Configuration builder lambda
 * @return Configured Json instance
 */
fun Json(from: Json = Json.Default, builderAction: JsonBuilder.() -> Unit): Json

String Serialization

Convert between Kotlin objects and JSON strings.

/**
 * Serialize a value to JSON string using explicit serializer
 * @param serializer Serialization strategy for type T
 * @param value Object to serialize
 * @return JSON string representation
 */
fun <T> Json.encodeToString(serializer: SerializationStrategy<T>, value: T): String

/**
 * Serialize a value to JSON string using reified type
 * @param value Object to serialize  
 * @return JSON string representation
 */
inline fun <reified T> Json.encodeToString(value: T): String

/**
 * Deserialize JSON string to object using explicit deserializer
 * @param deserializer Deserialization strategy for type T
 * @param string JSON string to parse
 * @return Deserialized object of type T
 */
fun <T> Json.decodeFromString(deserializer: DeserializationStrategy<T>, string: String): T

/**
 * Deserialize JSON string to object using reified type
 * @param string JSON string to parse
 * @return Deserialized object of type T
 */
inline fun <reified T> Json.decodeFromString(string: String): T

Usage Examples:

import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json

@Serializable
data class Person(val name: String, val age: Int, val city: String?)

// Serialization
val person = Person("Alice", 30, "New York")
val jsonString = Json.encodeToString(person)
// Result: {"name":"Alice","age":30,"city":"New York"}

// Deserialization
val deserializedPerson = Json.decodeFromString<Person>(jsonString)

// Custom Json configuration
val json = Json {
    prettyPrint = true
    ignoreUnknownKeys = true
}
val prettyJsonString = json.encodeToString(person)

JsonElement Serialization

Convert between Kotlin objects and JsonElement tree structures for programmatic JSON manipulation.

/**
 * Serialize a value to JsonElement using explicit serializer
 * @param serializer Serialization strategy for type T
 * @param value Object to serialize
 * @return JsonElement representation
 */
fun <T> Json.encodeToJsonElement(serializer: SerializationStrategy<T>, value: T): JsonElement

/**
 * Serialize a value to JsonElement using reified type
 * @param value Object to serialize
 * @return JsonElement representation  
 */
inline fun <reified T> Json.encodeToJsonElement(value: T): JsonElement

/**
 * Deserialize JsonElement to object using explicit deserializer
 * @param deserializer Deserialization strategy for type T
 * @param element JsonElement to deserialize
 * @return Deserialized object of type T
 */
fun <T> Json.decodeFromJsonElement(deserializer: DeserializationStrategy<T>, element: JsonElement): T

/**
 * Deserialize JsonElement to object using reified type
 * @param json JsonElement to deserialize
 * @return Deserialized object of type T
 */
inline fun <reified T> Json.decodeFromJsonElement(json: JsonElement): T

Usage Examples:

import kotlinx.serialization.json.*

@Serializable
data class Product(val id: Int, val name: String, val price: Double)

val product = Product(1, "Laptop", 999.99)

// Serialize to JsonElement
val jsonElement = Json.encodeToJsonElement(product)

// Manipulate JsonElement
val modifiedElement = buildJsonObject {
    jsonElement.jsonObject.forEach { (key, value) -> 
        put(key, value)
    }
    put("category", "Electronics")
}

// Deserialize back to object
val modifiedProduct = Json.decodeFromJsonElement<Product>(modifiedElement)

JSON Parsing

Parse JSON strings into JsonElement tree structures without requiring predefined data classes.

/**
 * Parse a JSON string into a JsonElement tree
 * @param string JSON string to parse
 * @return JsonElement representing the parsed JSON
 * @throws JsonDecodingException if the string is not valid JSON
 */
fun Json.parseToJsonElement(string: String): JsonElement

Usage Examples:

import kotlinx.serialization.json.*

// Parse JSON string to JsonElement
val jsonString = """
{
    "users": [
        {"name": "Alice", "active": true},
        {"name": "Bob", "active": false}
    ],
    "total": 2
}
"""

val jsonElement = Json.parseToJsonElement(jsonString)

// Navigate the JSON structure
val users = jsonElement.jsonObject["users"]?.jsonArray
val firstUser = users?.get(0)?.jsonObject
val userName = firstUser?.get("name")?.jsonPrimitive?.content
val isActive = firstUser?.get("active")?.jsonPrimitive?.boolean

val total = jsonElement.jsonObject["total"]?.jsonPrimitive?.int

Polymorphic Serialization

Support for serializing and deserializing polymorphic class hierarchies.

/**
 * Default class discriminator property name for polymorphic serialization
 */
val Json.classDiscriminator: String

/**
 * Mode controlling when class discriminator is included
 */
val Json.classDiscriminatorMode: ClassDiscriminatorMode

enum class ClassDiscriminatorMode {
    /** Never include class discriminator */
    NONE,
    /** Include discriminator for all JSON objects */
    ALL_JSON_OBJECTS, 
    /** Include only for polymorphic classes (default) */
    POLYMORPHIC
}

Usage Examples:

import kotlinx.serialization.*
import kotlinx.serialization.json.*

@Serializable
sealed class Animal {
    abstract val name: String
}

@Serializable
@SerialName("dog")
data class Dog(override val name: String, val breed: String) : Animal()

@Serializable  
@SerialName("cat")
data class Cat(override val name: String, val indoor: Boolean) : Animal()

// Configure Json for polymorphic serialization
val json = Json {
    classDiscriminator = "type"
    classDiscriminatorMode = ClassDiscriminatorMode.POLYMORPHIC
}

val animals = listOf<Animal>(
    Dog("Buddy", "Golden Retriever"),
    Cat("Whiskers", true)
)

val jsonString = json.encodeToString(animals)
// Result includes "type" discriminator field

val deserializedAnimals = json.decodeFromString<List<Animal>>(jsonString)

Error Handling

The Json class throws standard kotlinx.serialization exceptions:

  • SerializationException: Base exception for serialization errors
  • JsonDecodingException: Malformed JSON input
  • IllegalArgumentException: Invalid configuration or parameters
  • MissingFieldException: Required field missing during deserialization

These exceptions provide detailed error messages indicating the location and nature of serialization problems.

Install with Tessl CLI

npx tessl i tessl/maven-org-jetbrains-kotlinx--kotlinx-serialization-json-jvm

docs

advanced.md

annotations.md

builders.md

configuration.md

index.md

json-element.md

platform.md

serialization.md

tile.json