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

如何修改Groovy的strategy.groovy代码将字段值输出为指定数组格式

你当前的代码存在3个核心问题:

  • 循环逻辑错误:遍历players.item时,仍然读取整个rootStrategy.players_o.item集合的属性,没有用到当前迭代的对象,导致每次循环都取到全部球员的数组值
  • 节点结构不符合预期:你需要的是players_o下嵌套item数组结构,每个数组元素对应单个球员的属性,不是直接在strategy节点下平铺带点的字段
  • 字段名不匹配:预期输出的球员ID字段是talent_id_s,你代码里仍然用的是player_id_s

修正后的代码如下:

private createStrategyElement(rootStrategy, ctx) {
    Element strategy = new DefaultElement("strategy")
    // 先创建players_o父节点
    Element playersNode = strategy.addElement("players_o")
    // 遍历所有球员项
    rootStrategy.players_o.item.each { currentItem ->
        // 每个球员对应一个item子节点
        Element itemNode = playersNode.addElement("item")
        def component = currentItem.component
        // 赋值当前球员的属性
        itemNode.addElement("talent_id_s").text = component.player_id_s ?: ""
        itemNode.addElement("first_name_s").text = component.first_name_s ?: ""
        itemNode.addElement("last_name_s").text = component.last_name_s ?: ""
    }
    println("Value of strategy at line#146 "+strategy)
    return strategy
}

上面的代码用Groovy更简洁的each迭代代替for循环,同时用Groovy的空安全运算符?:简化非空判断逻辑,生成的节点结构会完全匹配你预期的JSON转换结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 00:39:03