github linkedin
Kotlin and YAML - Part 2
2016-02-27

Recently I blogged about Kotlin and SnakeYAML. I didn’t find a satisfying solution, so I tried another library for YAML parsing. Turns out that Jackson also supports YAML and even has a Kotlin module. Nice. Let’s give it a try!

I want to parse this YAML file:

# Size of the universe
universeSize:
  maxGalaxies: 1
  maxSystems: 3
  maxPlanets: 3

# Starter planet settings
starterPlanet:
  # Starting resources
  resources:
    crystal: 200
    gas: 100
    energy: 800

# Round time in seconds
roundTime: 5

into this set of data classes

data class UniverseSizeDto(val maxGalaxies: Int, val maxSystems: Int, val maxPlanets: Int)

data class ResourcesDto(val crystal: Int, val gas: Int, val energy: Int)

data class StarterPlanetDto(val resources: ResourcesDto)

data class ConfigDto(val universeSize: UniverseSizeDto, val starterPlanet: StarterPlanetDto, val roundTime: Int)

First, include Jackson and the needed modules:

dependencies {
  compile 'com.fasterxml.jackson.core:jackson-databind:2.7.1-1'
  compile 'com.fasterxml.jackson.module:jackson-module-kotlin:2.7.1-2'
  compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.7.1'
}

and write some code to parse the file:

fun loadFromFile(path: Path): ConfigDto {
    val mapper = ObjectMapper(YAMLFactory()) // Enable YAML parsing
    mapper.registerModule(KotlinModule()) // Enable Kotlin support

    return Files.newBufferedReader(path).use {
        mapper.readValue(it, ConfigDto::class.java)
    }
}

And it just works.

Only caveat: I now pull some more dependencies in my project, but I think that’s worth it. Here’s the output of gradle dependencies:

+--- com.fasterxml.jackson.core:jackson-databind:2.7.1-1
|    +--- com.fasterxml.jackson.core:jackson-annotations:2.7.0 -> 2.7.1
|    \--- com.fasterxml.jackson.core:jackson-core:2.7.1
+--- com.fasterxml.jackson.module:jackson-module-kotlin:2.7.1-2
|    +--- com.fasterxml.jackson.core:jackson-databind:2.7.1 -> 2.7.1-1 (*)
|    +--- com.fasterxml.jackson.core:jackson-annotations:2.7.1
|    \--- org.jetbrains.kotlin:kotlin-reflect:1.0.0
|         \--- org.jetbrains.kotlin:kotlin-stdlib:1.0.0 (*)
\--- com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.7.1
     +--- com.fasterxml.jackson.core:jackson-core:2.7.1
     \--- org.yaml:snakeyaml:1.15

Tags: kotlin

Back to posts