0
votes

I am getting json response in a request like Response=

[
  {
   "id":"1",
   "name":"Elfred",
   "city":"mexico",
    "@type":"author"
  },
  {
   "id":"2",
    "name":"michael",
    "city":"San Fransico",
    "@type":"Editor"}
]

I aM USING jsr223 Assertion I wanted to check my json Response contains keys : groovy Code:

    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";
}

I am getting Exception as

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)

What am i missing ??

1

1 Answers

0
votes

You're getting a JSON Array as the response, if you want to check each and every JSON Object which is inside the array so you need to amend your code like:

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'
    }
}

More information:

In general it's better to use a library like JSON Schema Validator rather than parsing the JSON manually, presumably you either should have a JSON Schema or it's possible to generate one.