You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jenkins Groovy中如何转换JSON数组以支持带索引的闭包遍历

解决Jenkins Groovy中JSONArray无法用闭包带索引遍历的问题

可行方案

方案1:转为Groovy List后使用eachWithIndex

将net.sf.json.JSONArray转为Groovy原生ArrayList,就能使用Groovy扩展的闭包遍历方法:

def groovyList = new ArrayList<>(array)
groovyList.eachWithIndex { item, index ->
    println item.name
    println item.age
    println "Index: ${index}"
}

方案2:手动通过索引遍历

利用JSONArray自带的size()和get()方法,用传统for循环实现带索引的遍历:

for (int i = 0; i < array.size(); i++) {
    def item = array.get(i)
    println item.name
    println item.age
    println "Index: ${i}"
}

方案3:遍历过程中手动维护索引

用普通each闭包配合计数器实现索引追踪:

def currentIndex = 0
array.each { item ->
    println item.name
    println item.age
    println "Index: ${currentIndex}"
    currentIndex++
}

问题原因

net.sf.json.JSONArray是Java实现的集合类,并未集成Groovy的eachWithIndex(你写的withEachIndex本身也不是Groovy标准方法)扩展方法。直接调用toArray()或toCollection()返回的仍是Java原生集合,同样不会自动应用Groovy的闭包扩展,因此需要转为Groovy原生List或者手动处理索引逻辑。

内容的提问来源于stack exchange,提问作者Paul Atreides

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 16:10:10