Groovy JsonBuilder构建多地区工位JSON结构出错求助
预期JSON格式
我拥有地点列表和工位列表,期望生成如下结构的JSON:
{ "Company": "my company", "Locations": { "India": { "cubicals": [ "A-8954","B-3212" ] }, "USA": { "cubicals": [ "A-8954","B-3212" ] } } }
编写的Groovy代码
cubicalList和nationsList已定义,原代码如下:
cubicalList=["A-8954","B-3212"] nationsList=["India", "USA"] def json = new groovy.json.JsonBuilder() name="my company" json { company name Locations { "${nationsList}" ( { cubicals cubicalsList } ) } } println json.toPrettyString()
问题描述
当前代码生成的结果将India和USA合并为一个键,而非作为Locations下的独立键,错误输出如下:
{ "company": "my company", "Locations": { "[India, USA]": { "cubicals": [ "A-8954", "B-3212" ] } } }
解决方案
问题根源是直接将整个nationsList作为键名,Groovy会把列表转为字符串[India, USA]作为单个键。需要遍历国家列表,为每个国家单独生成键值对,同时修正原代码的笔误和键名大小写问题:
修复后的代码
cubicalList=["A-8954","B-3212"] nationsList=["India", "USA"] def json = new groovy.json.JsonBuilder() name="my company" json { Company name // 修正键名大小写,匹配预期的"Company" Locations { // 遍历每个国家,生成独立的键值对 nationsList.each { nation -> "$nation" { cubicals cubicalList } } } } println json.toPrettyString()
关键修正点
- 用
each循环遍历nationsList,为每个国家创建Locations下的独立键 - 修正原代码中
company的大小写,使其与预期的Company键名一致 - 修正原代码中的笔误:将
cubicalsList改为正确的变量名cubicalList
内容的提问来源于stack exchange,提问作者R_SS
相关产品推荐
相关产品推荐

