SoapUI使用Groovy脚本如何动态提取JSON响应的货币字段
Groovy JsonSlurper 动态取货币属性解决方案
问题根因
- 你解析后的
slurperResponse是数组结构(接口响应最外层为[]),需要先取数组首个元素才能拿到国家属性对象 currencies字段是Map结构而非数组,你之前通过字符串截取获取货币代码的方式不可靠,直接取Map的键集即可拿到动态货币代码- 硬编码
currencies.RUB.name用的是Groovy Map的固定key点语法,动态key需要用方括号语法取值
修改后可运行代码
import groovy.json.JsonSlurper def responseContent = testRunner.testCase.getTestStepByName("CountryCode").getPropertyValue("Response") def slurperResponse = new JsonSlurper().parseText(responseContent) // 取第一个国家对象的货币Map def currencyMap = slurperResponse[0].currencies // 动态获取货币代码(单货币场景直接取第一个key,多货币可遍历) def dynamicCurrencyCode = currencyMap.keySet().first() // 动态传入货币代码取对应属性 def currencyName = currencyMap[dynamicCurrencyCode].name def currencySymbol = currencyMap[dynamicCurrencyCode].symbol // 验证输出 println "货币代码:${dynamicCurrencyCode}" println "货币名称:${currencyName}" println "货币符号:${currencySymbol}"
多货币场景适配
如果同一个国家返回多货币,直接遍历Map即可:
currencyMap.each { code, info -> println "货币代码:${code},货币名称:${info.name},货币符号:${info.symbol}" }
内容的提问来源于stack exchange,提问作者Arah
相关产品推荐
相关产品推荐

