在测试过程中遇到这样的一种场景,下一个接口的某个字段入参为一个json对象,该对象的值是上一个接口返回的内容,但是其中的某个值不是,需要修改后才能作为下个接口的入参整体传入
上一个接口返回的内容如下:
{"status": "SUCCESS","code": "0000","msg": "处理成功","payload": [{"schemeName": "内外","orderScheme": null,"createdDate": "2024-06-04T00:30:52.000+00:00","list": [{"startAccount": "AAA","targetAccount": "BBB","accountName": "内","orderAccount": 1,"orderScheme": null,"currency": "RMB","amount": null},{"startAccount": "AAA","targetAccount": "BBB","accountName": "外","orderAccount": 5,"orderScheme": null,"currency": "USD","amount": null}]}]
}
下一个接口的入参为payload中的所有内容,但是amount的值来源另外一个接口
解决办法如下:
使用后置脚本beanshell实现如下
import org.json.*;//获取请求返回值
String response_data = prev.getResponseDataAsString();// 格式转换成json对象
JSONObject data_obj = new JSONObject(response_data);
if(data_obj.get("payload").equals(null)){log.info("接口返回数据为空");
} else{
JSONArray payload_array=data_obj.getJSONArray("payload"); //将payload转成数组
log.info(data_obj.toString());// 获取payload的第一组数据:payload[0]
JSONObject payload_0 = (JSONObject)payload_array.getJSONObject(0);
log.info(payload_0.toString());//list转成数组
JSONArray list_array=payload_0.getJSONArray("list");
JSONObject list_0 = (JSONObject)list_array.getJSONObject(0);
log.info("list 0 的值:");
log.info(list_0.toString());Interpreter interpreter = new Interpreter();
interpreter.set("list_0", list_0);
// 提取上一步骤设置的金额
String set_amount = vars.get("amount");
log.info(set_amount);list_0.put("amount", set_amount);log.info(list_0.toString());
// 将修改后的字典设置参数
vars.put("currencySwapKeyPath",list_array.toString());
}