在 Kotlin 中读取 YAML 文件
Reading from a YAML file in Kotlin
我很难弄清楚如何在 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')
为什么?
您需要包含 jackson-dataformat-yaml
依赖项,然后像这样创建您的 ObjectMapper:
val mapper = ObjectMapper(YAMLFactory()).registerModule(KotlinModule())
我很难弄清楚如何在 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')
为什么?
您需要包含 jackson-dataformat-yaml
依赖项,然后像这样创建您的 ObjectMapper:
val mapper = ObjectMapper(YAMLFactory()).registerModule(KotlinModule())