Search code examples
javajsonjmeterbeanshell

Validating JSON Response using Beanshell in jmeter


I am trying to assert Json response in my jmeter using Beanshell assertion . Here is my code below.

import org.json.JSONObject;
import org.json.JSONArray;
import java.lang.String;
import org.apache.log.Logger;

try{
  String jsonString = prev.getResponseDataAsString();
  JsonObject jsonobj = JsonObject.readFrom(jsonString);
  JsonArray jsonarr = jsonobj.get("items").asArray();
  String pickup = jsonarr.get(2).asObject().get("CM_NAME").asString();
  log.info(pickup); 
 }
catch(Exception e)
{
 log.info("beanshell Exception "+e.getMessage());
}

Here is the Json path which i have to validate

$.items[2].CM_NAME

After i run the script i get the following script.

Assertion failure message: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``import org.json.JSONObject; import org.json.JSONArray; import java.lang.String; . . . '' : Typed variable declaration : Class: JsonObject not found in namespace

I am using jmeter version 2.11. Can anyone help me to get my script working correctly and is my code correct ?


Solution

  • I would suggest you to use JsonPath instead, which is exactly doing what you want to do.

    Also, upgrade to JMeter 3.1 which already embeds this library in its classpath, or download the JAR file and put it in /lib/ext.

    Full code example:

    import com.jayway.jsonpath.JsonPath;
    
    String author0 = JsonPath.read(document, "$.store.book[0].author");
    Failure = !"John Smith".equals(author0);
    if (Failure) {
      FailureMessage = "Expected John Smith as author";
    }