Jmeter中JSONObject和JSONArray的使用

Use of JSONObject and JSONArray in Jmeter

我在为 Amazon Kinesis 构建 Json 时遇到问题。 此 json 必须具有以下格式:

{
    "Records": [
        {
            "Data": "XzxkYXRhPl8x",
            "PartitionKey": "partitionKey1"
        },
        {
            "Data": "f1PxFQo92Afh",
            "PartitionKey": "partitionKey2"
        },
        {
            "Data": "Gi4sEdd08HypA",
            "PartitionKey": "partitionKey3"
        }
    ],
    "StreamName": "exampleStreamName"
}

我使用 BeanShell 采样器创建 json 作为缓冲区:

import org.json.JSONArray;
import org.json.JSONObject;


//Dichiarazione variabili
int timestampValue=(${startTime}+${i}+1);
float current_powerValue=${current_power_1}+${__Random(0,10)};
String idValue=${__threadNum}+"_"+"5";
JSONObject part = new JSONObject();


//Create JSON

part.put("timestamp",timestampValue);
part.put("parent","${__threadNum}");
part.put("id",idValue);
part.put("state","on");
part.put("today_kwh",65);
part.put("current_power",current_powerValue);
part.put("today_on_time",0);
part.put("on_for",0);
part.put("today_standby_time",0);

//ADD json to array
if(${i}%(${bufferSize}*${sample}-1)==0 && ${i}!=0 || ${i}==${totalNumber}-${endOfDb}){
    //Add to json variable the last json created
    vars.put("json",vars.get("json")+part.toString());
    //Make an JSONObject by json variable of jmeter
    JSONObject tempArray= new JSONObject(vars.get("json"));
    log.info(tempArray.toString());
    //Add tempArray into JSONArray so that it adds square brackets
    JSONArray records= new JSONArray();
    records.put(tempArray);
    //Add the second field streamName
    JSONObject kinesis = new JSONObject();
    kinesis.put("records",records);
    kinesis.put("streamName","kinesis");
    //save into jsonBuffer
    vars.put("jsonBuffer",kinesis.toString());
    //restart json variable
    vars.put("json","");    
}
else{
    //add new json into variable so to store it.
    vars.put("json", vars.get("json")+part.toString()+",");
}

我在 jmeter 中使用 json 变量为每次迭代保存 json,当 "i" 变量遵守 if 子句时,我开始创建 json结构体。 所以我将最后一个 json 添加到 jmeter 变量,然后我创建一个 JSONObject 来存储这个 json 但是当我这样做时它只存储一个 json (因为它是一个对象)。 不幸的是,如果我存储在 JSONArray 中,它会添加“”,因为将变量 json 作为字符串读取。 最好的解决方案是只使用 JSONObject 和 JSONArray 但我如何对所有迭代使用相同的对象(在 jmeter 中我不能使用 JSONArray) 这是我的jmx

您可以使用此代码段:

if(${i}%(${bufferSize}*${sample}-1)==0 && ${i}!=0 || ${i}==${totalNumber}-${endOfDb}){
 vars.put("json",vars.get("json")+part.toString());
 JSONArray records= new JSONArray("["+vars.get("json")+"]");
 log.info(records.toString());
 //records.put(tempArray);
 JSONObject kinesis = new JSONObject();
 kinesis.put("records",records);
 kinesis.put("streamName","kinesis");
 vars.put("jsonBuffer",kinesis.toString());
 vars.put("json",""); 
}