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

如何使用JsonSlurper()提取CanonicalMessage中Payload的CaseTitle值?

使用JsonSlurper提取嵌套JSON中的CaseTitle值

实现步骤

  • 初始化JsonSlurper实例,解析顶层JSON数据
  • 遍历InputParameters数组,筛选出key为CanonicalMessage的元素
  • 对该元素的value字段(嵌套JSON字符串)再次使用JsonSlurper解析
  • 提取Payload节点下的CaseTitle值,赋值到目标属性

完整代码示例

import groovy.json.JsonSlurper

// 输入的JSON字符串
def inputJson = '''{
    "Id": "db338737-af14-ef11-9f8a-000d3aad8ef7",
    "InputParameters": [
        {
            "key": "CanonicalMessage",
            "value": "{\"ActivityId\":\"9f368268\",\"Payload\":{\"CaseTitle\":\"Material Description 000\",\"CustomerAssetNumber\":\"104628\"}}"
        },
        {
            "key": "transactionlogid",
            "value": "9f36828e9"
        }
    ]
}'''

def slurper = new JsonSlurper()
def topLevelData = slurper.parseText(inputJson)

// 找到CanonicalMessage项
def canonicalMsgItem = topLevelData.InputParameters.find { it.key == 'CanonicalMessage' }

if (canonicalMsgItem) {
    // 解析嵌套的JSON字符串
    def canonicalMsgData = slurper.parseText(canonicalMsgItem.value)
    // 提取CaseTitle并设置属性
    def caseTitle = canonicalMsgData.Payload.CaseTitle
    // 替换为你的目标属性赋值逻辑,比如:
    // targetObject.caseTitle = caseTitle
    println "提取到的CaseTitle: $caseTitle"
} else {
    println "未找到key为CanonicalMessage的参数项"
}

代码说明

  • JsonSlurper.parseText()方法将JSON字符串解析为Groovy原生的Map/List结构,支持直接通过键名访问节点
  • 使用find方法在列表中快速匹配目标元素,比手动遍历更简洁高效
  • 注意CanonicalMessage的value是JSON格式的字符串,必须二次解析才能访问内部的Payload节点

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 05:02:13