Jmeter-解析返回参数-解析并操作json

工作中经常会遇到JSON字符串,接口的入参和返回参数也多数是JSON格式,自动化项目中常需要写脚本处理返回结果,本文总结java或jmeter的beanshell脚本中对于json的常用操作

json字符串的格式

  1. 简单的JSON字符串:{“key”:“value”,“key”:“value”…} 如:{“id”:“1001”,“name”:“晓春”,“sex”:“男”}

  2. JSON数组:[{“key”:“value”,“key”:“value”…},{},{}] 如:“data”:[{“id”:“1001”,“name”:“晓春”,“sex”:“男”},{“id”:“1002”,“name”:“小李”,“sex”:“男”}]

  3. 复杂的JSON字符串:值本身还是一个json字符串, 如:{“id”:“1001”,“name”:“晓春”,“sex”:“男”,“hobby”:{“hobby1”:“游泳”,“hobby2”:“打篮球”}},我们能够发现hobby对应的值依旧是一个json字符串({“hobby1”:“游泳”,“hobby2”:“打篮球”})

JSON字符串的解析方式

  1. 对于以上第一种格式的使用 get(“id”)能拿到1001
  2. 对于以上第二种格式的使用 getJSONArray(“data”)能拿到json数组:[{“id”:“1001”,“name”:“晓春”,“sex”:“男”},{“id”:“1002”,“name”:“小李”,“sex”:“男”}]
  3. 对于以上第三种格式的使用 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);
}

打印结果:
在这里插入图片描述

你可能感兴趣的:(Jmeter,自动化测试,java,jmeter,json,java)