问题:取出一个复杂json中的一个值
JSON:
{
"success": true,
"content": {
"records": [{
"id": "1551335804967534",
"companyId": "1530581135975019",
"current_amount": 8466.63,
"amountChange": 749.0,
"coinChange": 86.0,
"frozenAmountChange": 0.0,
"frozenCoinChange": 0.0,
"gmtCreate": 1551335805000,
"financeItemCode": "11",
"bizId": "1534752737214452",
"coin_change": 86.0,
"amount_change": 749.0,
"currentCapital": 7503.33,
"currentCoin": 963.3,
"taskId": "1534752738451006"
}, {
"id": "1551335684979609",
"companyId": "1530581135975019",
"current_amount": 7631.63,
"amountChange": 39.9,
"coinChange": 85.0,
"frozenAmountChange": 0.0,
"frozenCoinChange": 0.0,
"gmtCreate": 1551335685000,
"financeItemCode": "11",
"bizId": "1534751373885786",
"coin_change": 85.0,
"amount_change": 39.9,
"currentCapital": 6754.33,
"currentCoin": 877.3,
"taskId": "1534751380310146"
}, {
"id": "1551321044982790",
"companyId": "1530581135975019",
1,在接口测试中,经常会遇到,响应的结果是复杂的json,这时要用beanshll写脚本把值提出来
第一步:写第一个接口,用json把预期结果的值取出来(当然也可以用脚本)在后置处理器中写脚本,把要取的key取出来
第二步 ,写第二个接口,这个接口要取出实际结果的值,这时,我们要beanshell的方式来取
第三步:写beanshell把实际结果的值取出来
代码如下:
import org.json.*;
import org.apache.jmeter.samplers.SampleResult;
import java.util.ArrayList;
import java.util.List;
import java.sql.ResultSet;
import java.io.*;
import java.text.DecimalFormat;
String data_success = vars.get("p_success");
String data_execute_price = vars.get("p_execute_price");
double DoubleExecutePprice = Double.parseDouble(data_execute_price) ;
//得到的字符串转成double
String response_data = prev.getResponseDataAsString();
String request_data = prev.getQueryString();
String tname = prev.getThreadName();
JSONObject data_obj = new JSONObject(response_data);
//得到数组records,并转成字符串
String apps_str = data_obj.get("content").get("records").toString();
log.info(">>>>数组的值>>>>>>>"+ apps_str);
//把得到的apps_str,转成JSONArray对像
JSONArray apps_array = new JSONArray(apps_str);
// String[] result = new String[apps_array.length()];
/**打印第一个值,佣金明细页面的佣金*/
appStr = apps_array.get(0).toString() ;
JSONObject app_obj = new JSONObject(appStr);
double name =(double) app_obj.get("coinChange");
//从app_obj这个对像中获得coinChange,转化成字符串
log.info("佣金明细页面的佣金,打印第一个 coinChange 的值:--"+ name);
if(!data_success.equals("true")) {
Failure = true;
FailureMessage = "事物失败:success不等于true,打印请求和响应的值"+ "请求的值:"+request_data+"响应的值:"+response_data;
log.info("--------------------------------------");
prev.setStopThread(true);
//如果断言失败,后面的接口不需要再跑,直接暂停
} else if( name != DoubleExecutePprice ) {
Failure = true;
FailureMessage = "事物失败";
}else{
log.info("佣金明细页面的佣金: "+ name);
log.info("已完成页面的佣金: "+ data_execute_price);
FailureMessage = "佣金和本金核对成功";
log.info("-------------------佣金和本金核对成功---------------------");
}