首页 > 解决方案 > 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)

我错过了什么??

标签: jsongroovyjmeter

解决方案


如果要检查数组内的每个 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或者可以生成一个。


推荐阅读