YAML
suggest changeYAML is a human-friendly data format used for configuration files, CI pipelines, Kubernetes manifests and OpenAPI specs. It is a superset of JSON: indentation replaces braces, and it adds comments, multi-line strings and anchors.
Kotlin has two good options:
- kaml adds YAML support to kotlinx.serialization. You use the same
@Serializableclasses as for JSON, and it has no reflection. It works on JVM, Android, JS and Native. - Jackson with its YAML data format and Kotlin module. Use it if your project already uses Jackson, or if you need to read several documents from one file.
This article covers:
- decoding and encoding data classes with kaml
- configuring output style, unknown keys and naming
- error messages with line numbers
- anchors, aliases and merge keys
- the untyped
YamlNodetree - polymorphism with sealed classes
- reading and writing files
- Jackson YAML, including multi-document files
- YAML type gotchas
For loading application config with layered overrides see Configuration files.
Setup
kaml needs the kotlinx.serialization compiler plugin. In build.gradle.kts:
plugins {
kotlin("jvm") version "2.4.21"
kotlin("plugin.serialization") version "2.4.21"
}
dependencies {
implementation("com.charleskorn.kaml:kaml:0.104.0")
}
kaml brings in kotlinx-serialization-core. You don't need kotlinx-serialization-json unless you also work with JSON.
Decoding and encoding
Mark classes with @Serializable and use Yaml.default:
import com.charleskorn.kaml.Yaml
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
@Serializable
data class Database(val url: String, val user: String, val poolSize: Int = 10)
@Serializable
data class Server(val host: String, val port: Int)
@Serializable
data class AppConfig(
val name: String,
val debug: Boolean,
val server: Server,
val database: Database,
val features: List<String>,
)
fun main() {
val text = """
# application settings
name: shop
debug: false
server:
host: 0.0.0.0
port: 8080
database:
url: jdbc:postgresql://localhost/shop
user: app
features:
- search
- "checkout"
- reviews
""".trimIndent()
val config = Yaml.default.decodeFromString<AppConfig>(text)
println(config)
println(config.database.poolSize)
println(Yaml.default.encodeToString(config.copy(debug = true)))
}
Output:
AppConfig(name=shop, debug=false, server=Server(host=0.0.0.0, port=8080), database=Database(url=jdbc:postgresql://localhost/shop, user=app, poolSize=10), features=[search, checkout, reviews])
10
name: "shop"
debug: true
server:
host: "0.0.0.0"
port: 8080
database:
url: "jdbc:postgresql://localhost/shop"
user: "app"
poolSize: 10
features:
- "search"
- "checkout"
- "reviews"
Things to note:
- The reified
decodeFromString<T>()andencodeToString()are extension functions fromkotlinx.serialization. Import them, or pass the serializer yourself:Yaml.default.decodeFromString(AppConfig.serializer(), text). - Comments are skipped when reading. They are not kept when you write the data back.
poolSizewas missing, so it got its default value. A missing property with no default throwsMissingRequiredPropertyException.- By default kaml quotes every string, writes default values, and writes lists in block style.
Configuring Yaml
Pass a YamlConfiguration to change how kaml reads and writes. Create the Yaml instance once and reuse it:
import com.charleskorn.kaml.SequenceStyle
import com.charleskorn.kaml.SingleLineStringStyle
import com.charleskorn.kaml.Yaml
import com.charleskorn.kaml.YamlConfiguration
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
enum class Level { DEBUG, INFO, WARN }
@Serializable
data class Job(
val name: String,
@SerialName("run-at") val runAt: String,
val level: Level = Level.INFO,
val retries: Int = 3,
val owner: String? = null,
val tags: List<String> = emptyList(),
)
val yaml = Yaml(
configuration = YamlConfiguration(
strictMode = false, // ignore unknown keys
encodeDefaults = false, // skip properties equal to their default
singleLineStringStyle = SingleLineStringStyle.Plain,
sequenceStyle = SequenceStyle.Flow,
)
)
fun main() {
val text = """
name: backup
run-at: "02:00"
level: WARN
owner: ~
tags: [nightly, db]
comment: this key is not in the class
""".trimIndent()
val job = yaml.decodeFromString<Job>(text)
println(job)
println(yaml.encodeToString(job))
println("---")
println(Yaml.default.encodeToString(job))
}
Output:
Job(name=backup, runAt=02:00, level=WARN, retries=3, owner=null, tags=[nightly, db])
name: backup
run-at: 02:00
level: WARN
tags: [nightly, db]
---
name: "backup"
run-at: "02:00"
level: "WARN"
retries: 3
owner: null
tags:
- "nightly"
- "db"
~, null and an empty value all decode to null. Enums are matched by name. @SerialName renames a single property.
Options you will use most often:
| Option | Default | Effect |
|---|---|---|
strictMode |
true |
Throw on keys with no matching property. false ignores them |
encodeDefaults |
true |
Write properties whose value equals the default |
singleLineStringStyle |
DoubleQuoted |
Plain, PlainExceptAmbiguous, SingleQuoted |
multiLineStringStyle |
same as single-line | Literal (|), Folded (>), quoted, plain |
sequenceStyle |
Block |
Flow writes [a, b] |
encodingIndentationSize |
2 |
Spaces per indent level |
sequenceBlockIndent |
0 |
Extra indent for - items in block lists |
yamlNamingStrategy |
null |
SnakeCase, KebabCase, PascalCase, CamelCase |
polymorphismStyle |
Tag |
Property uses a type: key instead of a YAML tag |
anchorsAndAliases |
Forbidden |
Permitted(maxAliasCount) allows &anchor and *alias |
decodeEnumCaseInsensitive |
false |
Accept warn for WARN |
Be careful with SingleLineStringStyle.Plain. It writes run-at: 02:00 without quotes. kaml reads that back as the string 02:00, but a YAML 1.1 parser (PyYAML, SnakeYAML 1.x/2.x, older Ruby) reads it as the number 7200. The next section shows the safer PlainExceptAmbiguous.
Naming strategy and multi-line strings
YAML files often use snake_case keys. Instead of adding @SerialName to every property, set a naming strategy:
import com.charleskorn.kaml.MultiLineStringStyle
import com.charleskorn.kaml.SingleLineStringStyle
import com.charleskorn.kaml.Yaml
import com.charleskorn.kaml.YamlConfiguration
import com.charleskorn.kaml.YamlNamingStrategy
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
@Serializable
data class Release(
val versionName: String,
val countryCode: String,
val enabled: String,
val startTime: String,
val buildNumber: String,
val releaseNotes: String,
)
fun main() {
val text = """
version_name: 1.10
country_code: NO
enabled: yes
start_time: 02:30
build_number: 0x1F
release_notes: |
Fixed login bug.
Faster startup.
""".trimIndent()
val yaml = Yaml(
configuration = YamlConfiguration(
yamlNamingStrategy = YamlNamingStrategy.SnakeCase,
singleLineStringStyle = SingleLineStringStyle.PlainExceptAmbiguous,
multiLineStringStyle = MultiLineStringStyle.Literal,
)
)
val r = yaml.decodeFromString<Release>(text)
println(r)
println(yaml.encodeToString(r))
}
Output:
Release(versionName=1.10, countryCode=NO, enabled=yes, startTime=02:30, buildNumber=0x1F, releaseNotes=Fixed login bug.
Faster startup.)
version_name: "1.10"
country_code: NO
enabled: yes
start_time: 02:30
build_number: "0x1F"
release_notes: |-
Fixed login bug.
Faster startup.
This shows the main advantage of typed decoding. Every property is a String, so kaml keeps the text exactly as written: 1.10 stays 1.10 (not 1.1), and NO stays NO (not false).
PlainExceptAmbiguous quotes values that look like numbers, booleans or null in YAML 1.2 ("1.10", "0x1F"). It does not quote NO, yes or 02:30, because those are only special in YAML 1.1. If other tools will read your file, DoubleQuoted (the default) is the safest choice.
The | block scalar keeps newlines. |- removes the final newline.
Errors with line numbers
Every kaml exception extends YamlException and carries line, column and path:
import com.charleskorn.kaml.Yaml
import com.charleskorn.kaml.YamlException
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
@Serializable
data class Server(val host: String, val port: Int)
@Serializable
data class Config(val name: String, val servers: List<Server>)
fun tryParse(text: String) {
try {
println(Yaml.default.decodeFromString<Config>(text))
} catch (e: YamlException) {
println("${e::class.simpleName} at line ${e.line}, column ${e.column} (${e.path.toHumanReadableString()})")
println(" ${e.message}")
}
}
fun main() {
tryParse("""
name: web
servers:
- host: a.example.com
port: 80
- host: b.example.com
port: eighty
""".trimIndent())
tryParse("""
name: web
servers:
- host: a.example.com
prot: 80
""".trimIndent())
tryParse("""
name: web
servers:
- host: a.example.com
port: 80
""".trimIndent())
tryParse("""
servers: []
""".trimIndent())
}
Output:
InvalidPropertyValueException at line 6, column 11 (servers[1].port)
Value for 'servers' is invalid: Value for 'port' is invalid: Value 'eighty' is not a valid integer value.
InvalidPropertyValueException at line 4, column 5 (servers[0].prot)
Value for 'servers' is invalid: Unknown property 'prot'. Known properties are: host, port
MalformedYamlException at line 4, column 3 (servers)
while parsing a block collection
at line 3, column 3:
- host: a.example.com
^
expected <block end>, but found '?'
at line 4, column 3:
port: 80
^
MissingRequiredPropertyException at line 1, column 1 (<root>)
Property 'name' is required but it is missing.
The second case shows why the default strictMode = true is useful: a typo like prot is reported instead of silently using a default value. Validate config at startup and print e.path and e.line so users can find the mistake.
Anchors, aliases and merge keys
Anchors (&name) mark a node, aliases (*name) reuse it, and the merge key << copies a map's entries into another map. kaml forbids anchors by default. This protects against "billion laughs" documents, where nested aliases expand to gigabytes of data. Turn them on with a limit:
import com.charleskorn.kaml.AnchorsAndAliases
import com.charleskorn.kaml.Yaml
import com.charleskorn.kaml.YamlConfiguration
import com.charleskorn.kaml.YamlException
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
@Serializable
data class Db(val host: String, val port: Int, val name: String)
@Serializable
data class Envs(val dev: Db, val prod: Db)
val text = """
base: &base
host: localhost
port: 5432
dev:
<<: *base
name: shop_dev
prod:
<<: *base
host: db.example.com
name: shop
""".trimIndent()
fun main() {
try {
Yaml.default.decodeFromString<Envs>(text)
} catch (e: YamlException) {
println("${e::class.simpleName}: ${e.message}")
}
val yaml = Yaml(
configuration = YamlConfiguration(
strictMode = false,
anchorsAndAliases = AnchorsAndAliases.Permitted(maxAliasCount = 100u),
)
)
val envs = yaml.decodeFromString<Envs>(text)
println(envs.dev)
println(envs.prod)
}
Output:
ForbiddenAnchorOrAliasException: Parsing anchors and aliases is disabled.
Db(host=localhost, port=5432, name=shop_dev)
Db(host=db.example.com, port=5432, name=shop)
Keys written next to << override the merged ones, so prod.host wins over base.host. strictMode = false is needed here because Envs has no base property.
The YamlNode tree
When the structure isn't known ahead of time, or you only need a few values, parse into a YamlNode tree. The node types are YamlMap, YamlList, YamlScalar, YamlNull and YamlTaggedNode:
import com.charleskorn.kaml.Yaml
import com.charleskorn.kaml.YamlList
import com.charleskorn.kaml.YamlMap
import com.charleskorn.kaml.YamlNode
import com.charleskorn.kaml.YamlNull
import com.charleskorn.kaml.YamlScalar
import com.charleskorn.kaml.yamlList
import com.charleskorn.kaml.yamlMap
import com.charleskorn.kaml.yamlScalar
import kotlinx.serialization.Serializable
@Serializable
data class Step(val name: String, val run: String)
fun describe(node: YamlNode, indent: String = "") {
when (node) {
is YamlMap -> node.entries.forEach { (key, value) ->
println("$indent${key.content}:")
describe(value, "$indent ")
}
is YamlList -> node.items.forEachIndexed { i, item ->
println("$indent[$i]")
describe(item, "$indent ")
}
is YamlScalar -> println("$indent${node.content}")
is YamlNull -> println("${indent}null")
else -> println("$indent(other: ${node::class.simpleName})")
}
}
fun main() {
val text = """
name: CI
on: [push, pull_request]
timeout: 30
env: ~
steps:
- name: build
run: ./gradlew build
- name: test
run: ./gradlew test
""".trimIndent()
val root = Yaml.default.parseToYamlNode(text).yamlMap
println(root.getScalar("name")?.content)
println(root.getScalar("timeout")?.toInt()?.plus(5))
println(root.get<YamlList>("on")?.items?.map { it.yamlScalar.content })
println(root.get<YamlNode>("env") is YamlNull)
println(root.get<YamlNode>("missing"))
// decode only part of the document into a typed class
val stepsNode = root.get<YamlNode>("steps")!!
val steps = Yaml.default.decodeFromYamlNode<List<Step>>(stepsNode)
println(steps)
println()
describe(root.get<YamlNode>("steps")!!.yamlList.items[0])
}
Output:
CI
35
[push, pull_request]
true
null
[Step(name=build, run=./gradlew build), Step(name=test, run=./gradlew test)]
name:
build
run:
./gradlew build
- A
YamlScalarstores the raw text incontent. Convert it withtoInt(),toLong(),toDouble()ortoBoolean(). get<T>(key)returnsnullfor a missing key. TheyamlMap,yamlListandyamlScalarextension properties cast a node and throw if it has a different type.decodeFromYamlNode()turns any subtree into a typed object. This is handy for plugin-style config where each section is decoded by a different module.
Polymorphism with sealed classes
A list can hold different types if they share a @Serializable sealed interface. By default kaml marks the type with a YAML tag (!<http>). Most hand-written YAML uses a type: key instead, so set PolymorphismStyle.Property:
import com.charleskorn.kaml.PolymorphismStyle
import com.charleskorn.kaml.Yaml
import com.charleskorn.kaml.YamlConfiguration
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
@Serializable
sealed interface Check
@Serializable
@SerialName("http")
data class HttpCheck(val url: String, val expectStatus: Int = 200) : Check
@Serializable
@SerialName("tcp")
data class TcpCheck(val host: String, val port: Int) : Check
@Serializable
data class Monitor(val interval: Int, val checks: List<Check>)
fun main() {
val yaml = Yaml(
configuration = YamlConfiguration(
polymorphismStyle = PolymorphismStyle.Property,
polymorphismPropertyName = "type",
)
)
val text = """
interval: 60
checks:
- type: http
url: https://example.com/health
- type: tcp
host: db.internal
port: 5432
""".trimIndent()
val m = yaml.decodeFromString<Monitor>(text)
println(m)
println(yaml.encodeToString(m))
// the default style uses YAML tags
println(Yaml.default.encodeToString(m))
val tagged = """
interval: 30
checks:
- !<tcp>
host: cache.internal
port: 6379
""".trimIndent()
println(Yaml.default.decodeFromString<Monitor>(tagged))
}
Output:
Monitor(interval=60, checks=[HttpCheck(url=https://example.com/health, expectStatus=200), TcpCheck(host=db.internal, port=5432)])
interval: 60
checks:
- type: "http"
url: "https://example.com/health"
expectStatus: 200
- type: "tcp"
host: "db.internal"
port: 5432
interval: 60
checks:
- !<http>
url: "https://example.com/health"
expectStatus: 200
- !<tcp>
host: "db.internal"
port: 5432
Monitor(interval=30, checks=[TcpCheck(host=cache.internal, port=6379)])
@SerialName on each subclass sets the value used in type:. Without it, the fully qualified class name is used. An unknown type throws UnknownPolymorphicTypeException.
Reading and writing files
On the JVM, decodeFromStream() and encodeToStream() work with InputStream and OutputStream. The top-level value can be a map:
import com.charleskorn.kaml.Yaml
import com.charleskorn.kaml.decodeFromStream
import com.charleskorn.kaml.encodeToStream
import kotlinx.serialization.Serializable
import java.nio.file.Files
import kotlin.io.path.createTempFile
import kotlin.io.path.inputStream
import kotlin.io.path.outputStream
import kotlin.io.path.readText
@Serializable
data class Limits(val cpu: Double, val memoryMb: Int)
@Serializable
data class Service(val image: String, val replicas: Int, val env: Map<String, String>, val limits: Limits)
fun main() {
val services = mapOf(
"web" to Service("nginx:1.29", 3, mapOf("TZ" to "UTC"), Limits(0.5, 256)),
"api" to Service("shop-api:2.4.1", 2, mapOf("LOG_LEVEL" to "info", "PORT" to "8080"), Limits(1.0, 512)),
)
val path = createTempFile("services", ".yaml")
path.outputStream().use { Yaml.default.encodeToStream(services, it) }
println(path.readText())
val loaded: Map<String, Service> = path.inputStream().use { Yaml.default.decodeFromStream(it) }
println(loaded["api"]?.env?.get("PORT"))
println(loaded == services)
Files.delete(path)
}
Output:
"web":
image: "nginx:1.29"
replicas: 3
env:
"TZ": "UTC"
limits:
cpu: 0.5
memoryMb: 256
"api":
image: "shop-api:2.4.1"
replicas: 2
env:
"LOG_LEVEL": "info"
"PORT": "8080"
limits:
cpu: 1.0
memoryMb: 512
8080
true
Map entries keep their insertion order. For a config file inside your JAR, use object {}.javaClass.getResourceAsStream("/app.yaml")!! as the input stream. On multiplatform, use decodeFromSource() and encodeToSink(), which take Okio types.
Jackson YAML
If your project already uses Jackson for JSON, add the YAML data format. Jackson 3 uses the tools.jackson group:
dependencies {
implementation("tools.jackson.dataformat:jackson-dataformat-yaml:3.2.3")
implementation("tools.jackson.module:jackson-module-kotlin:3.2.3")
}
Classes need no annotations. The Kotlin module uses reflection to call the primary constructor, with support for default values and nullability. Jackson can also read files with several documents separated by ---, which kaml can't do:
import tools.jackson.databind.JsonNode
import tools.jackson.dataformat.yaml.YAMLMapper
import tools.jackson.dataformat.yaml.YAMLWriteFeature
import tools.jackson.module.kotlin.kotlinModule
import tools.jackson.module.kotlin.readValue
data class Container(val name: String, val image: String, val ports: List<Int> = emptyList())
data class Manifest(val kind: String, val metadata: Map<String, String>, val containers: List<Container> = emptyList())
val mapper: YAMLMapper = YAMLMapper.builder()
.addModule(kotlinModule())
.disable(YAMLWriteFeature.WRITE_DOC_START_MARKER)
.enable(YAMLWriteFeature.MINIMIZE_QUOTES)
.build()
fun main() {
val one = """
kind: Pod
metadata:
name: web
containers:
- name: nginx
image: nginx:1.29
ports: [80, 443]
""".trimIndent()
val pod = mapper.readValue<Manifest>(one)
println(pod)
print(mapper.writeValueAsString(pod))
// several documents separated by ---
val many = """
kind: Namespace
metadata:
name: shop
---
kind: Pod
metadata:
name: api
containers:
- name: api
image: shop-api:2.4.1
""".trimIndent()
mapper.readerFor(Manifest::class.java).readValues<Manifest>(many).use { docs ->
for (doc in docs) println("${doc.kind} ${doc.metadata["name"]}")
}
// untyped tree
val tree: JsonNode = mapper.readTree(one)
println(tree.at("/containers/0/ports/1").asInt())
}
Output:
Manifest(kind=Pod, metadata={name=web}, containers=[Container(name=nginx, image=nginx:1.29, ports=[80, 443])])
kind: Pod
metadata:
name: web
containers:
- name: nginx
image: nginx:1.29
ports:
- 80
- 443
Namespace shop
Pod api
443
- Without
disable(WRITE_DOC_START_MARKER), Jackson starts the output with---. MINIMIZE_QUOTESwrites plain strings where it is safe to do so. By default Jackson quotes all strings.readTree()returns the sameJsonNodetree as for JSON, soat("/json/pointer"),path()andget()all work.YAMLMapperis thread-safe and expensive to build. Keep one instance.- Jackson 3 ignores unknown keys by default. Add
.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)to the builder to catch typos in config files. - Jackson does not expand aliases or
<<merge keys into regular data. If your files use them, use kaml.
YAML type gotchas
In untyped data, the parser decides each value's type from the text. Here Jackson reads into Map<String, Any?>:
import tools.jackson.dataformat.yaml.YAMLMapper
import tools.jackson.module.kotlin.readValue
fun main() {
val text = """
country: NO
enabled: yes
debug: true
start: 02:30
version: 1.10
port: 8080
id: 007
empty:
""".trimIndent()
val map = YAMLMapper().readValue<Map<String, Any?>>(text)
for ((k, v) in map) println("$k = $v (${v?.let { it::class.simpleName }})")
}
Output:
country = NO (String)
enabled = yes (String)
debug = true (Boolean)
start = 02:30 (String)
version = 1.1 (Double)
port = 8080 (Int)
id = 007 (String)
empty = null (null)
version: 1.10became the number1.1. Quote version strings in YAML ("1.10"), or decode into aStringproperty.- kaml and Jackson 3 follow YAML 1.2, where only
trueandfalseare booleans. In YAML 1.1 parsers,NO,yes,onandoffare booleans and02:30is a base-60 number. This is the "Norway problem": a country code list turnsNOintofalse. - With kaml, decoding
yesinto aBooleanproperty fails withValue 'yes' is not a valid boolean, permitted choices are: true or false. Integers accept hex such as0x1F90. - An empty value is
null, not an empty string. Write""for an empty string. - Tabs can't be used for indentation. Mixing indent widths in one block is a syntax error.
kaml or Jackson?
| kaml | Jackson YAML | |
|---|---|---|
| Model classes | @Serializable + compiler plugin |
Plain classes, reflection |
| Platforms | JVM, Android, JS, Native | JVM only |
| Unknown keys | Error by default (strictMode) |
Ignored by default in Jackson 3 (FAIL_ON_UNKNOWN_PROPERTIES) |
| Anchors and aliases | Opt-in with a limit, merge keys work | Not resolved for normal data |
| Multiple documents per file | No | readValues() |
| Error locations | Line, column and property path | Line and column |
| Shares models with | kotlinx.serialization JSON, CBOR, Protobuf | Jackson JSON, XML, CSV |
Choose kaml for new Kotlin code, especially multiplatform code or code that already uses kotlinx.serialization. Choose Jackson when the rest of the application uses Jackson, or when you process multi-document files such as Kubernetes manifests.