CtrlK
BlogDocsLog inGet started
Tessl Logo

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

Kotlin multiplatform JSON serialization library with JavaScript-specific dynamic object conversion capabilities

Pending
Overview
Eval results
Files

core-operations.mddocs/

Core JSON Operations

Primary JSON serialization and deserialization functionality providing the essential methods for converting between Kotlin objects and JSON strings, with comprehensive configuration options.

Capabilities

Json Factory Functions

Create Json instances with custom configurations.

/**
 * Creates a Json instance with default configuration
 */
fun Json(builderAction: JsonBuilder.() -> Unit = {}): Json

/**
 * Creates a Json instance copying configuration from another Json instance
 * @param from Base Json instance to copy configuration from
 * @param builderAction Additional configuration changes
 */
fun Json(from: Json, builderAction: JsonBuilder.() -> Unit): Json

/**
 * Default Json instance with standard configuration
 */
object Json {
    companion object {
        val Default: Json
    }
}

Usage Examples:

// Default Json instance
val json = Json.Default

// Custom configuration
val customJson = Json {
    ignoreUnknownKeys = true
    prettyPrint = true
    coerceInputValues = true
}

// Copy and modify existing configuration
val derivedJson = Json(customJson) {
    encodeDefaults = true
}

String Serialization

Encode Kotlin objects to JSON strings and decode JSON strings back to Kotlin objects.

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

/**
 * Serializes the given value to a JSON string using reified type serializer
 * @param value The value to serialize
 * @return JSON string representation
 */
inline fun <reified T> Json.encodeToString(value: T): String

/**
 * Deserializes the given JSON string to a value using the given deserializer
 * @param deserializer Deserialization strategy for type T
 * @param string JSON string to deserialize
 * @return Deserialized value
 * @throws JsonDecodingException if string is malformed
 */
fun <T> Json.decodeFromString(deserializer: DeserializationStrategy<T>, string: String): T

/**
 * Deserializes the given JSON string to a value using reified type deserializer
 * @param string JSON string to deserialize
 * @return Deserialized value
 * @throws JsonDecodingException if string is malformed
 */
inline fun <reified T> Json.decodeFromString(string: String): T

Usage Examples:

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

val json = Json { prettyPrint = true }
val person = Person("Alice", 30)

// Serialize with reified type
val jsonString = json.encodeToString(person)
// Result: {"name":"Alice","age":30}

// Serialize with explicit serializer
val jsonString2 = json.encodeToString(Person.serializer(), person)

// Deserialize with reified type  
val parsed = json.decodeFromString<Person>(jsonString)

// Deserialize with explicit deserializer
val parsed2 = json.decodeFromString(Person.serializer(), jsonString)

JsonElement Serialization

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

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

/**
 * Serializes the given value to a JsonElement using reified type serializer
 * @param value The value to serialize
 * @return JsonElement representation
 */
inline fun <reified T> Json.encodeToJsonElement(value: T): JsonElement

/**
 * Deserializes the given JsonElement to a value using the given deserializer
 * @param deserializer Deserialization strategy for type T
 * @param element JsonElement to deserialize
 * @return Deserialized value
 * @throws JsonDecodingException if element structure is invalid
 */
fun <T> Json.decodeFromJsonElement(deserializer: DeserializationStrategy<T>, element: JsonElement): T

/**
 * Deserializes the given JsonElement to a value using reified type deserializer
 * @param element JsonElement to deserialize
 * @return Deserialized value
 * @throws JsonDecodingException if element structure is invalid
 */
inline fun <reified T> Json.decodeFromJsonElement(element: JsonElement): T

/**
 * Parses the given JSON string to a JsonElement
 * @param string JSON string to parse
 * @return JsonElement tree representation
 * @throws JsonDecodingException if string is malformed
 */
fun Json.parseToJsonElement(string: String): JsonElement

Usage Examples:

@Serializable
data class Config(val host: String, val port: Int, val ssl: Boolean)

val json = Json.Default
val config = Config("localhost", 8080, true)

// Serialize to JsonElement
val element = json.encodeToJsonElement(config)
// element is JsonObject containing the data

// Access JsonElement programmatically
val jsonObject = element.jsonObject
val host = jsonObject["host"]?.jsonPrimitive?.content
val port = jsonObject["port"]?.jsonPrimitive?.int

// Deserialize from JsonElement
val parsedConfig = json.decodeFromJsonElement<Config>(element)

// Parse string to JsonElement
val jsonString = """{"host":"server.com","port":443,"ssl":true}"""
val parsedElement = json.parseToJsonElement(jsonString)
val configFromParsed = json.decodeFromJsonElement<Config>(parsedElement)

Error Handling

JSON operations can throw specific exceptions for different types of errors.

/**
 * Exception thrown during JSON encoding
 */
class JsonEncodingException(message: String) : SerializationException(message)

/**
 * Exception thrown during JSON decoding
 */
class JsonDecodingException(message: String) : SerializationException(message)

Error Handling Examples:

try {
    val result = json.decodeFromString<Person>("""{"name":"John"}""") // missing "age"
} catch (e: JsonDecodingException) {
    println("Failed to decode: ${e.message}")
}

try {
    val malformedJson = """{"name":"John", "age":}""" // invalid syntax
    val result = json.parseToJsonElement(malformedJson)
} catch (e: JsonDecodingException) {
    println("Malformed JSON: ${e.message}")
}

Common Patterns

Working with Nullable Values

@Serializable  
data class User(val name: String, val email: String?)

val json = Json { 
    explicitNulls = false // Don't include null values in output
}

val user = User("Bob", null)
val jsonString = json.encodeToString(user)
// Result: {"name":"Bob"} (email omitted)

Handling Unknown Properties

val json = Json {
    ignoreUnknownKeys = true // Ignore extra properties during deserialization
}

val jsonWithExtra = """{"name":"Alice","age":25,"country":"US"}"""
val person = json.decodeFromString<Person>(jsonWithExtra) // Works despite extra "country"

Pretty Printing

val json = Json {
    prettyPrint = true
    prettyPrintIndent = "  " // Use 2 spaces for indentation
}

val formatted = json.encodeToString(person)
// Result:
// {
//   "name": "Alice",
//   "age": 25
// }

Install with Tessl CLI

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

docs

builder-dsl.md

configuration.md

core-operations.md

custom-serializers.md

dynamic-conversion.md

index.md

json-annotations.md

json-element.md

tile.json