jackson 在 Kotlin 中 读取 YAML 文件

avkwfej4  于 2022-11-08  发布在  Kotlin
关注(0)|答案(2)|浏览(377)

我很难弄清楚如何在Kotlin中读取YAML文件。
简而言之,YAML具有以下格式:

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

我已经创建了这些数据类:

data class Account (
        val id: String
)

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

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

然后,我尝试使用以下语句解析该文件:

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)

printlnException in thread "main" com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'aws': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')而失败
为什么?

2nbm6dog

2nbm6dog1#

您需要包含jackson-dataformat-yaml相依性,然后建立ObjectMapper,如下所示:

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

iq0todco2#

另一种方法是使用Kaml
将以下依赖项添加到build.gradle.kts

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

然后将@Serializable注解添加到数据类中:

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

然后可以从YAML中解析它:

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

相关问题