1
votes

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 ?

2

2 Answers

1
votes

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

If you really want to go this way you need to ensure you have the relevant JSON library somewhere in JMeter Classpath (usually it is enough to drop the jar to JMeter's "lib" folder and restart JMeter to pick it up)


Going forward I would recommend using different approaches like:

  1. There is JSON Path Assertion available via JMeter Plugins, you can use your JSON Path query directly there. You can install JSON Path Assertion via JMeter Plugins Manager

    JSON Plugins JMeter Plugin Manager

  2. Switch to JSR223 Assertion and Groovy language. Groovy has built-in JSON support so you won't require any extra libraries. For example if you have the following JSON Response:

    {
      "items": [
        {
          "CM_NAME": "foo"
        },
        {
          "CM_NAME": "bar"
        },
        {
          "CM_NAME": "baz"
        }
      ]
    }
    

    and you need to extract baz value you can do it using the following Groovy code:

    def response = SampleResult.getResponseDataAsString()
    def json = new groovy.json.JsonSlurper().parseText(response)
    
    log.info(json.items[2].CM_NAME)
    

    Groovy JSON Example