使用SnakeYAML将YAML文件转为Groovy Map时格式不符合预期
Groovy中SnakeYAML解析YAML后的Map格式调整方案
核心问题说明
- 结构问题:你当前拿到的是包含
maintainers键的外层Map,而你期望的是maintainers对应的内部列表数据。 - 字符串引号问题:实际输出中字符串不带引号是Groovy对集合默认
toString()方法的表现,解析后的字符串本身是正常的String类型,并非解析错误。
解决方案
1. 正确获取目标列表数据
加载YAML后,直接提取maintainers对应的列表即可,而不是返回整个外层Map:
Yaml yaml = new Yaml() Map yamlMap = yaml.load(yamlFile) // 取出maintainers对应的列表,这就是你期望的核心数据结构 List<Map> maintainersList = yamlMap.maintainers
此时maintainersList就是你期望输出中的两个Map组成的列表,可直接用于搜索操作,比如根据component名称查找:
// 示例:搜索component为PowerPuff Girls的条目 def target = maintainersList.find { it.component == 'PowerPuff Girls' }
2. 输出带引号的格式化内容
如果需要打印出类似期望输出的带引号格式,可以通过自定义逻辑实现,比如使用Groovy的JsonBuilder快速格式化:
import groovy.json.JsonBuilder def builder = new JsonBuilder(maintainersList) // 输出格式化后的带引号内容 println builder.toPrettyString()
输出效果会接近你的期望:
[ { "component": "PowerPuff Girls", "pg": "Utonium Labs", "people": [ "Buttercup", "Blossom", "Bubbles" ], "files": [ "sugar/*", "spice/*", "things/*nice*", "chemicalx/*" ] }, { "component": "Gangreen Gang", "pg": "Villians", "people": [ "Ace", "Snake", "Big Billy" ], "files": [ "ace/*", "snake/*" ] } ]
也可以手动遍历构建自定义格式:
maintainersList.each { entry -> def formattedEntry = entry.collect { key, value -> if (value instanceof List) { def listContent = value.collect { "'$it'" }.join(', ') "$key: [$listContent]" } else { "$key: '$value'" } }.join(', ') println "[$formattedEntry]" }
输出结果:
[component: 'PowerPuff Girls', pg: 'Utonium Labs', people: ['Buttercup', 'Blossom', 'Bubbles'], files: ['sugar/*', 'spice/*', 'things/*nice*', 'chemicalx/*']] [component: 'Gangreen Gang', pg: 'Villians', people: ['Ace', 'Snake', 'Big Billy'], files: ['ace/*', 'snake/*']]
3. 纠正之前的错误用法
你尝试的yamlMap['maintainers']['component']会报错,因为yamlMap['maintainers']是一个List,不是单个Map,要获取某个条目的component,需要通过索引或者遍历:
// 获取第一个条目的component def firstComponent = yamlMap['maintainers'][0]['component'] // 遍历所有条目获取component列表 def allComponents = yamlMap['maintainers'].collect { it.component }
内容的提问来源于stack exchange,提问作者wolpurgisnacht
相关产品推荐
相关产品推荐

