如何在Groovy脚本中解析JSON获取最后一个parameter元素值
Groovy解析嵌套JSON获取最后一个parameter值
问题原因
你之前的代码def error = payload.childInstances.parameter返回null,原因有两个:
childInstances是数组类型(JSON里用[]包裹),不是单个对象,直接访问数组的parameter属性自然返回null;- 目标
parameter位于多层嵌套的childInstances最内层,需要逐层遍历或递归查找才能定位。
解决方案
方式一:固定结构逐层遍历(适用于JSON结构固定的场景)
如果你的JSON嵌套层级固定,可以直接逐层访问到目标节点:
import groovy.json.JsonSlurper // 先解析JSON字符串为Groovy对象 def jsonSlurper = new JsonSlurper() def payload = jsonSlurper.parseText(yourJsonContent) // 逐层进入嵌套的childInstances数组(每层取第一个元素) def targetInstance = payload.childInstances[0] .childInstances[0] .childInstances[0] .childInstances[0] .childInstances[0] // 获取parameter数组的第一个元素(目标内容) def errorMessage = targetInstance.parameter[0]
方式二:递归查找(适用于JSON嵌套层级不固定的场景)
如果嵌套层级可能变化,用递归方法收集所有parameter值,再取最后一个:
import groovy.json.JsonSlurper def jsonSlurper = new JsonSlurper() def payload = jsonSlurper.parseText(yourJsonContent) // 递归收集所有parameter内容 def collectAllParameters(obj, params = []) { // 如果当前对象有parameter属性,加入列表 if (obj.parameter) { params.addAll(obj.parameter) } // 如果有childInstances,遍历每个子节点继续收集 if (obj.childInstances) { obj.childInstances.each { child -> collectAllParameters(child, params) } } return params } // 获取所有parameter,取最后一个 def allParams = collectAllParameters(payload) def lastError = allParams.last()
验证结果
两种方式最终得到的lastError就是你需要的内容:
com.sap.esb.oauth.token.access.TokenAccessException: OAuth2 Authorization Code Credential 'OAUTH_MSOFFICE65_CRED' not found
内容的提问来源于stack exchange,提问作者Rick
相关产品推荐
相关产品推荐

