在 Kotlin 中读取 YAML 文件
我很难弄清楚如何读取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
在线程“ main” com.fasterxml中使用异常失败。
I'm having a hard time trying to figure out how to read a YAML file in Kotlin.
In short, the YAML has the following format:
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')
Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要包含
jackson-dataformat-yaml
依赖项,然后像这样创建 ObjectMapper:You need to include the
jackson-dataformat-yaml
dependency and then create your ObjectMapper like this:另一种方法是使用 Kaml:
将以下依赖项添加到您的
build.gradle.kts< /code>
然后将@Serialized注释添加到您的数据类:
然后您可以从YAML解析它:
An alternative would be to use Kaml:
Add the following dependency to your
build.gradle.kts
Then add @Serializable annotation to your data classes:
Then you can parse it from YAML:
添加依赖项:
创建映射器:
Add dependencies:
Create mapper: