简体   繁体   English

从 Kotlin 中的 YAML 文件读取

[英]Reading from a YAML file in Kotlin

I'm having a hard time trying to figure out how to read a YAML file in Kotlin.我很难弄清楚如何在 Kotlin 中读取 YAML 文件。

In short, the YAML has the following format:简而言之,YAML 的格式如下:

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') 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?为什么?

You need to include the jackson-dataformat-yaml dependency and then create your ObjectMapper like this:您需要包含jackson-dataformat-yaml依赖项,然后像这样创建您的 ObjectMapper:

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

An alternative would be to use Kaml :另一种方法是使用Kaml

Add the following dependency to your build.gradle.kts将以下依赖项添加到您的build.gradle.kts

implementation("com.charleskorn.kaml:kaml:0.46.0")

Then add @Serializable annotation to your data classes:然后将 @Serializable 注解添加到您的数据类中:

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

Then you can parse it from YAML:然后你可以从 YAML 解析它:


val parsedYaml = Yaml.default.decodeFromString(Cloud.serializer(), Path.of("accounts.yaml").toFile().readText())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM