JSON Schema DSL
Table of contents
For manual schema construction, use the kt-schema-json module. It provides type-safe Kotlin models compliant with the JSON Schema Draft 2020-12 specification and a DSL for building JSON Schema definitions programmatically, with full kotlinx-serialization support.
kotlin
dependencies {
implementation("me.kpavlov.kt.schema:kt-schema-json:<version>")
}Quick Example
kotlin
val schema = jsonSchema {
property("id") {
required = true
string { format = "uuid" }
}
property("email") {
required = true
string { format = "email" }
}
property("age") {
integer {
minimum = 0.0
maximum = 150.0
}
}
// Polymorphic types with discriminators
property("role") {
oneOf {
discriminator(propertyName = "type") {
"admin" mappedTo "#/definitions/AdminRole"
"user" mappedTo {
property("type") { string { constValue = "user" } }
property("permissions") { array { ofString() } }
}
}
}
}
}Features
- โ Type-safe property definitions (string, number, integer, boolean, array, object, reference)
- โ Polymorphism: oneOf, anyOf, allOf with elegant discriminator support
- โ
Type-safe enums: Native Kotlin types (
List<String>,List<Number>, etc.) instead ofJsonElement - โ Constraints: required, nullable, enum, const, min/max, format validation
- โ Nested schemas and arrays of complex types
- โ Full kotlinx-serialization integration
- โ Kotlin Multiplatform support
๐ For comprehensive documentation, see kt-schema-json/README.md covering:
- Complete DSL reference and type-safe enum API
- Polymorphism patterns (oneOf, anyOf, allOf) with discriminators
- Generic properties with heterogeneous enums
- Working with nested objects and arrays
- Serialization/deserialization examples
- Function calling schema for LLM APIs
See Also
- Generated Schemas โ the same model, produced from your classes instead of by hand
- Validation Constraints โ the keywords generators emit from annotations