如何在Groovy中移除GET请求响应冗余部分以使用JsonSlurper
问题背景
从REST接口获取的requestInfo字符串包含冗余内容(URI、HTTP版本、Headers及Content:标识),需要仅保留Content:后的JSON结构,用于JsonSlurper解析。示例冗余内容如下:
URI: https://apiext.thisurl.com/ado/v1/listener
HTTP Version: 1.1
Headers:
{
Authorization: Basic ********
Content-Type: application/json; charset=utf-8
}
Content:
{
"subscriptionId": "5898cfds-aafds2223335-423004422e"
"notificationId": 13869
"id": "846714a-b461e-449e-9600-f68a9975d2f4"
"eventType": "workitem.updated"
"publisherId": "tfs"
"message": {
"text": "User Story #2202091 (0819 ado 2) update)"
"html": "<a href="https://dev.azure.com/zsETO/web/wi.aspx?pcguid=931ea459-abea-43db-9aed-eb489dee1e5e&id=22221">User Story #2202091 (0819 ado 2) updated by Darren"
"markdown": "<a href="https://dev.azure.com/ZionsETO/web/wi.aspx?pcguid=931ea459-abea-43db-9aed-eb489dee1e5e&id=2202091" rel="nofollow noreferrer">User Story #2202091</a> (0819 ado 2) updated by Darre"
}
此前尝试使用requestInfo.drop(70)截取,但因URI长度不固定,无法适配所有场景。
解决方案
基于关键字Content:定位JSON起始位置,动态截取目标内容,同时处理可能的JSON语法错误:
def notificationDetails = subscriptionService.getNotificatonsDetails(collection, subId, notificationId) def requestInfo = "${notificationDetails.details.request}" // 定位Content:关键字的结束位置,截取后续内容 def contentMarker = 'Content:' def contentStartIdx = requestInfo.indexOf(contentMarker) + contentMarker.length() def rawJson = requestInfo.substring(contentStartIdx).trim() // 使用JsonSlurper解析,兼容可能的语法错误 def slurper = new groovy.json.JsonSlurper() def jsonData try { jsonData = slurper.parseText(rawJson) } catch (groovy.json.JsonException e) { // 修复常见JSON语法问题:缺失逗号、格式不规范 def fixedJson = rawJson .replaceAll('"(\\w+)"\\s*:', '"$1":') // 统一键值对格式 .replaceAll('(?<!,)\\s*"', ', "') // 在缺失逗号的地方添加 .replaceAll('^, ', '') // 移除开头多余的逗号 .replaceAll('\\}\\s*$', '}') // 确保结尾闭合 jsonData = slurper.parseText(fixedJson) } // 后续处理解析后的JSON数据 // println(jsonData.subscriptionId)
说明
- 动态定位:通过
indexOf找到Content:的位置,不管前面冗余内容长度如何,都能准确获取JSON起始点 - 容错处理:针对示例中JSON缺失逗号的情况,添加了简单的语法修复逻辑,避免解析失败
- 兼容性:适用于所有
requestInfo结构一致但冗余内容长度可变的场景
内容的提问来源于stack exchange,提问作者mangel

