Home > Software engineering >  Reading from a YAML file in Kotlin
Reading from a YAML file in Kotlin

Time:04-01

I'm having a hard time trying to figure out how to read a YAML file in Kotlin.

In short, the YAML has the following format:

aws:
  foo:
    dev:
      id: '1111'
    pro:
      id: '2222'
  bar:
    dev:
      id: '3333'
    pro:
      id: '4444'

I have created these data classes:

data class Account (
        val id: String
)

data class Owner (
        val accounts: List<Account>
)

data class Cloud (
        val owners: List<Owner>
)

And then I try to parse the file with:

val mapper = ObjectMapper().registerModule(KotlinModule())
val settings: Cloud = mapper.readValue(Path.of("accounts.yaml").toFile())
# also tried this
val settings: List<Cloud> = mapper.readValue(Path.of("accounts.yaml").toFile())
println(settings)

the println fails with Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'aws': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')

Why?

CodePudding user response:

You need to include the jackson-dataformat-yaml dependency and then create your ObjectMapper like this:

val mapper = ObjectMapper(YAMLFactory()).registerModule(KotlinModule())
  • Related