我很难弄清楚如何在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)
println
因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')
而失败
为什么?
2条答案
按热度按时间2nbm6dog1#
您需要包含
jackson-dataformat-yaml
相依性,然后建立ObjectMapper,如下所示:iq0todco2#
另一种方法是使用Kaml:
将以下依赖项添加到
build.gradle.kts
然后将@Serializable注解添加到数据类中:
然后可以从YAML中解析它: