Kotlin multiplatform JSON serialization library with type-safe, reflectionless approach supporting all platforms
—
Comprehensive configuration system for customizing JSON encoding and decoding behavior through builder pattern.
Builder class for configuring Json instances with mutable properties for all configuration options.
/**
* Builder for Json instance configuration provided by Json { ... } factory function
*/
class JsonBuilder {
/** Whether default values of Kotlin properties should be encoded. Default: false */
var encodeDefaults: Boolean
/** Whether null values should be encoded for nullable properties. Default: true */
var explicitNulls: Boolean
/** Whether encounters of unknown properties should be ignored. Default: false */
var ignoreUnknownKeys: Boolean
/** Removes JSON specification restriction and makes parser more liberal. Default: false */
var isLenient: Boolean
/** Whether resulting JSON should be pretty-printed. Default: false */
var prettyPrint: Boolean
/** Indent string to use with prettyPrint mode. Default: " " (4 spaces) */
var prettyPrintIndent: String
/** Enables coercing incorrect JSON values. Default: false */
var coerceInputValues: Boolean
/** Name of class descriptor property for polymorphic serialization. Default: "type" */
var classDiscriminator: String
/** Defines which classes should have class discriminator added. Default: POLYMORPHIC */
var classDiscriminatorMode: ClassDiscriminatorMode
/** Whether Json instance makes use of JsonNames annotation. Default: true */
var useAlternativeNames: Boolean
/** JsonNamingStrategy for all properties in classes. Default: null */
var namingStrategy: JsonNamingStrategy?
/** Enables decoding enum values in case-insensitive manner. Default: false */
var decodeEnumsCaseInsensitive: Boolean
/** Allows parser to accept trailing commas. Default: false */
var allowTrailingComma: Boolean
/** Allows parser to accept C/Java-style comments. Default: false */
var allowComments: Boolean
/** Removes restriction on special floating-point values (NaN, Infinity). Default: false */
var allowSpecialFloatingPointValues: Boolean
/** Enables structured objects to be serialized as map keys. Default: false */
var allowStructuredMapKeys: Boolean
/** Switches polymorphic serialization to array format. Default: false */
var useArrayPolymorphism: Boolean
/** Module with contextual and polymorphic serializers. Default: EmptySerializersModule */
var serializersModule: SerializersModule
}Immutable configuration object containing all Json behavior settings.
/**
* Configuration of current Json instance available through Json.configuration
* Standalone configuration object is read-only and cannot create new Json instances
*/
class JsonConfiguration(
val encodeDefaults: Boolean = false,
val ignoreUnknownKeys: Boolean = false,
val isLenient: Boolean = false,
val allowStructuredMapKeys: Boolean = false,
val prettyPrint: Boolean = false,
val explicitNulls: Boolean = true,
val prettyPrintIndent: String = " ",
val coerceInputValues: Boolean = false,
val useArrayPolymorphism: Boolean = false,
val classDiscriminator: String = "type",
val allowSpecialFloatingPointValues: Boolean = false,
val useAlternativeNames: Boolean = true,
val namingStrategy: JsonNamingStrategy? = null,
val decodeEnumsCaseInsensitive: Boolean = false,
val allowTrailingComma: Boolean = false,
val allowComments: Boolean = false,
val classDiscriminatorMode: ClassDiscriminatorMode = ClassDiscriminatorMode.POLYMORPHIC
)Control how Kotlin objects are encoded to JSON.
Usage Examples:
@Serializable
data class User(val name: String, val age: Int = 25, val email: String? = null)
// encodeDefaults: Include properties with default values
val withDefaults = Json { encodeDefaults = true }
val user = User("Alice")
println(withDefaults.encodeToString(user))
// {"name":"Alice","age":25,"email":null}
val withoutDefaults = Json { encodeDefaults = false }
println(withoutDefaults.encodeToString(user))
// {"name":"Alice"}
// explicitNulls: Control null value encoding
val explicitNulls = Json { explicitNulls = true }
val implicitNulls = Json { explicitNulls = false }
val userWithNull = User("Bob", email = null)
println(explicitNulls.encodeToString(userWithNull))
// {"name":"Bob","email":null}
println(implicitNulls.encodeToString(userWithNull))
// {"name":"Bob"}
// prettyPrint: Format JSON for readability
val pretty = Json {
prettyPrint = true
prettyPrintIndent = " " // 2 spaces
}
println(pretty.encodeToString(user))
/*
{
"name": "Alice",
"age": 25
}
*/Control how JSON is decoded to Kotlin objects.
Usage Examples:
@Serializable
data class Config(val timeout: Int, val retries: Int)
// ignoreUnknownKeys: Handle extra properties in JSON
val lenient = Json { ignoreUnknownKeys = true }
val strict = Json { ignoreUnknownKeys = false }
val jsonWithExtra = """{"timeout":5000,"retries":3,"unknown":"value"}"""
val config1 = lenient.decodeFromString<Config>(jsonWithExtra)
// Success: Config(timeout=5000, retries=3)
// strict.decodeFromString<Config>(jsonWithExtra)
// Would throw SerializationException
// coerceInputValues: Handle invalid values
val coercing = Json { coerceInputValues = true }
enum class Status { ACTIVE, INACTIVE }
@Serializable
data class Account(val id: Int = 1, val status: Status = Status.ACTIVE)
val invalidJson = """{"id":null,"status":"UNKNOWN"}"""
val account = coercing.decodeFromString<Account>(invalidJson)
// Result: Account(id=1, status=ACTIVE) - uses defaults for invalid values
// isLenient: Accept malformed JSON
val lenientParser = Json { isLenient = true }
val malformedJson = """{key: "value", another: 123}""" // Unquoted keys
val parsed = lenientParser.parseToJsonElement(malformedJson)Handle special cases like floating-point values and structured map keys.
Usage Examples:
// allowSpecialFloatingPointValues: Handle NaN and Infinity
val specialFloats = Json { allowSpecialFloatingPointValues = true }
val floats = listOf(1.0, 2.0, Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY)
val encoded = specialFloats.encodeToString(floats)
// [1.0,2.0,NaN,Infinity,-Infinity]
val decoded = specialFloats.decodeFromString<List<Double>>(encoded)
// allowStructuredMapKeys: Use objects as map keys
val structuredKeys = Json { allowStructuredMapKeys = true }
@Serializable
data class Point(val x: Int, val y: Int)
val mapWithObjectKeys = mapOf(
Point(1, 2) to "first",
Point(3, 4) to "second"
)
val encoded = structuredKeys.encodeToString(mapWithObjectKeys)
// [{"x":1,"y":2},"first",{"x":3,"y":4},"second"] - flat array formatControl how polymorphic types are handled during serialization.
Usage Examples:
@Serializable
sealed class Shape
@Serializable
data class Circle(val radius: Double) : Shape()
@Serializable
data class Rectangle(val width: Double, val height: Double) : Shape()
// classDiscriminator: Change discriminator property name
val customDiscriminator = Json {
classDiscriminator = "shapeType"
}
val circle: Shape = Circle(5.0)
val encoded = customDiscriminator.encodeToString(circle)
// {"shapeType":"Circle","radius":5.0}
// useArrayPolymorphism: Use array format for polymorphism
val arrayPoly = Json { useArrayPolymorphism = true }
val arrayEncoded = arrayPoly.encodeToString(circle)
// ["Circle",{"radius":5.0}]
// classDiscriminatorMode: Control when discriminator is added
val allObjects = Json {
classDiscriminatorMode = ClassDiscriminatorMode.ALL_JSON_OBJECTS
}
@Serializable
data class Container(val shape: Shape, val metadata: Map<String, String>)
val container = Container(circle, mapOf("color" to "red"))
// Adds discriminator to all JSON objects, not just polymorphic onesEnable relaxed JSON parsing for development and configuration files.
Usage Examples:
val relaxed = Json {
allowComments = true
allowTrailingComma = true
ignoreUnknownKeys = true
}
val jsonWithComments = """
{
// Configuration file
"database": {
"host": "localhost", // Development host
"port": 5432,
/*
* Connection pool settings
*/
"maxConnections": 10,
}, // Trailing comma allowed
"features": [
"auth",
"logging", // Another trailing comma
]
}
"""
val config = relaxed.parseToJsonElement(jsonWithComments)Configure custom serializers and polymorphic serialization rules.
Usage Examples:
val module = SerializersModule {
polymorphic(Shape::class) {
subclass(Circle::class)
subclass(Rectangle::class)
}
contextual(UUID::class, UUIDSerializer)
}
val configuredJson = Json {
serializersModule = module
classDiscriminator = "type"
ignoreUnknownKeys = true
}
// Now polymorphic serialization works automatically
val shapes: List<Shape> = listOf(Circle(3.0), Rectangle(4.0, 5.0))
val encoded = configuredJson.encodeToString(shapes)
val decoded = configuredJson.decodeFromString<List<Shape>>(encoded)Install with Tessl CLI
npx tessl i tessl/maven-org-jetbrains-kotlinx--kotlinx-serialization-json