Jmeter解析返回参数以及解析并操作json方式
作者:xiaobai178
本文总结了Java或JMeter的BeanShell脚本中处理JSON字符串的常用操作,包括解析JSON数组、JSON对象和嵌套的JSON字符串,并提供了示例代码和打印结果
Jmeter解析返回参数并操作json
工作中经常会遇到JSON字符串,接口的入参和返回参数也多数是JSON格式,自动化项目中常需要写脚本处理返回结果,本文总结java或jmeter的beanshell脚本中对于json的常用操作
json字符串的格式
- 简单的JSON字符串:
{“key”:“value”,“key”:“value”…} 如:{“id”:“1001”,“name”:“晓春”,“sex”:“男”}
- JSON数组:
[{“key”:“value”,“key”:“value”…},{},{}] 如:“data”:[{“id”:“1001”,“name”:“晓春”,“sex”:“男”},{“id”:“1002”,“name”:“小李”,“sex”:“男”}]
- 复杂的JSON字符串:
值本身还是一个json字符串, 如:
{“id”:“1001”,“name”:“晓春”,“sex”:“男”,“hobby”:{“hobby1”:“游泳”,“hobby2”:“打篮球”}}
我们能够发现hobby对应的值依旧是一个json字符串
({“hobby1”:“游泳”,“hobby2”:“打篮球”})
JSON字符串的解析方式
- 对于以上第一种格式的使用 get(“id”)能拿到1001
- 对于以上第二种格式的使用 getJSONArray(“data”)能拿到json数组:[{“id”:“1001”,“name”:“晓春”,“sex”:“男”},{“id”:“1002”,“name”:“小李”,“sex”:“男”}]
- 对于以上第三种格式的使用 getJSONObject(“hobby”)能拿到json对象:{“hobby1”:“游泳”,“hobby2”:“打篮球”}
注意jmeter中打印要转换成string
示例代码:
import org.json.JSONObject; import org.json.JSONArray; String content = "{'students':[{'stu_id':'1001','stu_name':'十一郎'}," + "{'stu_id':'1002','stu_name':'十二郎'}],'flag':'1'," + "'teacher':{'tea_id':'2001','tea_name':'晓春'}}"; //将string转为json JSONObject json_content = new JSONObject(content); //json中嵌套的json要用getJSONObject(); list要用getJSONArray(); 一级key直接用get("key")来拿到value JSONArray studentsData = json_content.getJSONArray("students"); String teacherData = json_content.getJSONObject("teacher").toString(); String teaId = json_content.getJSONObject("teacher").get("tea_id").toString(); log.info("这是studentsData:"+studentsData); log.info("这是teacherData:"+teacherData); log.info("这是teaId:"+teaId); //循环studentsDataArray for(int i=0; i<studentsData.length(); i++){ String stuId = studentsData.get(i).get("stu_id").toString(); String stuName = studentsData.get(i).get("stu_name").toString(); log.info(stuId); log.info(stuName); }
打印结果:
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。