json - Jsr223 断言在 jmeter 中的 json 响应失败
问题描述
我在像 Response= 这样的请求中得到 json 响应
[
{
"id":"1",
"name":"Elfred",
"city":"mexico",
"@type":"author"
},
{
"id":"2",
"name":"michael",
"city":"San Fransico",
"@type":"Editor"}
]
我正在使用 jsr223 断言我想检查我的 json 响应包含键:groovy 代码:
import groovy.json.JsonSlurper;
import java.util.*;
def failureMessage = "";
def jsonResponse = null;
JsonSlurper JSON = new JsonSlurper ();
jsonResponse = JSON.parseText(prev.getResponseDataAsString());
if (!jsonResponse.keySet().containsAll("id","name","city","@type")) {
failureMessage += "The json config element has wrong structure.\n\n";
}
我得到异常
javax.script.ScriptException: groovy.lang.MissingMethodException: No signature of method: java.util.ArrayList.keySet() is applicable for argument types: () values: []
Possible solutions: toSet(), toSet(), set(int, java.lang.Object), set(int, java.lang.Object), get(int), get(int)
我错过了什么??
解决方案
如果要检查数组内的每个 JSON 对象,您将得到一个JSON 数组作为响应,因此您需要修改代码,例如:
def jsonResponse = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def failureMessage = ""
jsonResponse.each { entry ->
if (!entry.keySet().containsAll('id', 'name', 'city', '@type')) {
failureMessage += 'The json config element has wrong structure.\n\n'
}
}
更多信息:
一般来说,最好使用JSON Schema Validator之类的库,而不是手动解析 JSON,大概你应该有一个JSON Schema或者可以生成一个。
推荐阅读
- amazon-web-services - AWS Auto Scaling Fargate 任务根据 SQS 队列长度向上或向下
- swift - cvPixelBuffer 到 CGImage 的转换只给出黑白图像
- excel - Excel VBA / 导入默认大小的 WMF 图像会产生巨大的图像
- java - 如何从给定的 IPAddress 打印所有子网?
- excel - 连续平均每个其他单元格
- firebase - 当我只想过滤时,Firestore 返回排序的文档列表
- xunit - 在与功能文件不同的位置生成 feature.cs 文件 - SpecFlow.xUnit 3.6.23
- excel - 将二维分层数据分解为关系数据库
- javascript - 服务器错误错误:无效的挂钩调用。Hooks 只能在 _app.js 中的函数组件内部调用
- salesforce - Visual force 页面中的按钮禁用