4

Our Requirement is we need to convert the Json response into Java object. May i know how to do it in Jmeter? Can we use Beanshell?

Here is my sample response

{"items":[],"indicators":
[{"name":"location","type":"country","title":"Country"},{"name":"total","type":"number","title":"Entities Total"}]

We are able to store into Csv or json format but how to convert this into Java object? Can any help us on this?

Chetan Joshi
  • 5,582
  • 4
  • 30
  • 43
Kavinkumar Muthu
  • 99
  • 1
  • 5
  • 14

3 Answers3

1

You can use BeanShell for processing this JSON. You can use json-smart that comes as part of JMeter 3.3 (I don't know about previous versions). Here you have example code to process your json and obtain "type" from the 1st element of array "indicators":

import net.minidev.json.parser.JSONParser;
import net.minidev.json.JSONObject;
import net.minidev.json.JSONArray;

JSONParser p = new JSONParser(JSONParser.MODE_PERMISSIVE);

String jsonString = prev.getResponseDataAsString();
JSONObject jsonObj = (JSONObject) p.parse(jsonString);
JSONArray arr = (JSONArray) jsonObj.get("indicators");

JSONObject indicator = (JSONObject) arr.get(0);
String typeString = (String) indicator.get("type");

log.info("TYPE:" + typeString);

vars.put("TYPEVAR", typeString);

BTW, the json you wrote is missing a final '}'.

rodolk
  • 5,606
  • 3
  • 28
  • 34
0

You can use beanshell like this Extracting JSON Response using Bean Shell Postprocessor

beanshell will help yo to get JSONObject and you can JSONObject to a pojo. How to efficiently map a org.json.JSONObject to a POJO?

Community
  • 1
  • 1
utkusonmez
  • 1,486
  • 15
  • 22
0

Use the JSON smart library that comes with JMeter. For sample code, refer the following answer or the one given by the previous answer.

You can then use vars.putObject and vars.getObject to store and retrieve objects and pass them around between samplers.

https://stackoverflow.com/a/42859821/7332423

enter image description here

Jmeter test plan test.jmx

<?xml version="1.0" encoding="UTF-8"?>
<jmeterTestPlan version="1.2" properties="2.9" jmeter="3.0 r1743807">
  <hashTree>
    <TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="Test Plan" enabled="true">
      <stringProp name="TestPlan.comments"></stringProp>
      <boolProp name="TestPlan.functional_mode">false</boolProp>
      <boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
      <elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
        <collectionProp name="Arguments.arguments"/>
      </elementProp>
      <stringProp name="TestPlan.user_define_classpath"></stringProp>
    </TestPlan>
    <hashTree>
      <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Thread Group" enabled="true">
        <stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
        <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Loop Controller" enabled="true">
          <boolProp name="LoopController.continue_forever">false</boolProp>
          <stringProp name="LoopController.loops">1</stringProp>
        </elementProp>
        <stringProp name="ThreadGroup.num_threads">1</stringProp>
        <stringProp name="ThreadGroup.ramp_time">1</stringProp>
        <longProp name="ThreadGroup.start_time">1490275382000</longProp>
        <longProp name="ThreadGroup.end_time">1490275382000</longProp>
        <boolProp name="ThreadGroup.scheduler">false</boolProp>
        <stringProp name="ThreadGroup.duration"></stringProp>
        <stringProp name="ThreadGroup.delay"></stringProp>
      </ThreadGroup>
      <hashTree>
        <DebugSampler guiclass="TestBeanGUI" testclass="DebugSampler" testname="Debug Sampler" enabled="true">
          <boolProp name="displayJMeterProperties">false</boolProp>
          <boolProp name="displayJMeterVariables">true</boolProp>
          <boolProp name="displaySystemProperties">false</boolProp>
        </DebugSampler>
        <hashTree>
          <BeanShellPreProcessor guiclass="TestBeanGUI" testclass="BeanShellPreProcessor" testname="BeanShell PreProcessor" enabled="true">
            <stringProp name="filename"></stringProp>
            <stringProp name="parameters"></stringProp>
            <boolProp name="resetInterpreter">false</boolProp>
            <stringProp name="script">import org.apache.commons.lang3.StringUtils;
import net.minidev.json.parser.JSONParser;
import net.minidev.json.JSONObject;
import net.minidev.json.JSONArray;

String sInputString =  "return {\"items\":[{\"STANDARDRATEFORMAT\":\"0.00\",\"ASSIGNED_HRS\":0,\"RESOURCE_NAME\":\"#Buddhika \",\"COST\":\"0.00\",\"PERCENTASSIGNED\":\"100.00\",\"EMAIL\":\"Buddhika75@mspblank.com\",\"AVAILABLEFROM\":\"10-May-2011\",\"ALLOCATED_HRS\":\"1872.00\",\"RESOURCE_ID\":36197221,\"AVAILABLETO\":\"31-Mar-2012\",\"calendar\":{\"exceptions\":{},\"weekDayHours\":{}}}]}";

//String sInputString = prev.getResponseDataAsString();

try {
     // Use StringUtils to cut the string between the two
    String sCutString = StringUtils.substringBetween(sInputString, "return {\"items", "]}");
    String sFinalString = "{\"items" + sCutString + "]}";
    log.info("sFinalString=" + sFinalString);

    // Use JSONParser to parse the JSON
    JSONParser parser = new JSONParser(JSONParser.ACCEPT_NON_QUOTE|JSONParser.ACCEPT_SIMPLE_QUOTE); 
    JSONObject rootObject = (JSONObject) parser.parse(sFinalString);
    //JSONObject rootObject = (JSONObject) parser.parse(prev.getResponseDataAsString());

    JSONArray jResourceArray = (JSONArray) rootObject.get("items");

    for (int i=0; i &lt; jResourceArray.size(); i++) {
        log.info(jResourceArray.get(i).toString());
        // You can access individual elements using this
        log.info("RESOURCE_ID=" + jResourceArray.get(i).get("RESOURCE_ID"));
    }


}
catch ( Exception ex) {
    log.info("Exception.." + ex);
}</stringProp>
          </BeanShellPreProcessor>
          <hashTree/>
        </hashTree>
      </hashTree>
    </hashTree>
  </hashTree>
</jmeterTestPlan>
henrebotha
  • 1,244
  • 2
  • 14
  • 36
Selva
  • 541
  • 5
  • 16
  • I used the mention code in your post and i modified but i am getting the below error:- ' jmeter.extractor.BeanShellPostProcessor: Problem in BeanShell script org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval In file: inline evaluation of: ``import org.apache.commons.lang3.StringUtils; import net.minidev.json.parser.JSON . . . '' Encountered "items" at line 6, column 27.' – Kavinkumar Muthu Mar 23 '17 at 06:03
  • added JMeter test plan and the output to the original answer. For the above code to work, you need to have the following jars in your JMeter\lib directory. commons-lang3-3.4.jar & json-smart-2.2.jar (any version). By default, it comes with your Jmeter installation. If you are still getting the error, ensure that your code is correct. You can get the above error even for a simple syntax issue – Selva Mar 23 '17 at 13:28