浅谈JSONObject解析JSON数据
2019-11-05 14:47 软件测试汪 阅读(3102) 评论(0) 编辑 收藏 举报我们在做jmeter接口测试时能会用beanshell断言,一般都会将返回值转成JSONObject对象进行处理。本文选取较为复杂json格式数据,也将适用于java接口测试。
JSON数据
{
"data": {
"city": "深圳",
"date": "2017-11-04",
"pm25": {
"aqi": 0,
"co": 8,
"updatetime": "2017-11-04 13:00:00"
},
"daily": [
{
"date": "2017-11-04",
"week": "星期六",
"templow": "19",
"weather": "多云"
},
{
"date": "2017-11-05",
"week": "星期日",
"sunrise": "06:29",
"weather": "多云"
}
]
},
"status": 0,
"msg": "ok"
}
解析JSON
以下代码使用HttpClient进行接口测试,同时使用testNg进行断言
package apitest.cases;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.net.URI;
public class Weather {
@Test
public void weather() {
HttpClient httpClient = HttpClientBuilder.create().build();
//执行post方法
try {
HttpGet httpGet = new HttpGet();
httpGet.setURI(URI.create("http://localhost:8001/weather"));
//声明一个对象来进行响应结果的存储
HttpResponse response = httpClient.execute(httpGet);
//获取响应结果将格式转化为Json数据
String response2 = EntityUtils.toString(response.getEntity(), "utf-8");
JSONObject responseJson = new JSONObject(response2);
// 获取msg status
String msg = responseJson.getString("msg");
String status = responseJson.get("status").toString();
// 获取data
JSONObject jsonData = responseJson.getJSONObject("data");
// 获取data里的city
String city = jsonData.getString("city");
// 获取pm25
JSONObject pm25 = jsonData.getJSONObject("pm25");
// 获取pm25里的updatetime
String updateTime = pm25.getString("updatetime");
// 获取data里的daily
JSONArray jsonDaily = jsonData.getJSONArray("daily");
// 获取data里的daily的第一组数据
JSONObject jsonDailyFirst = jsonDaily.getJSONObject(0);
// 获取data里的daily的第一组数据的date
String date = jsonDailyFirst.getString("date");
System.out.println("获取msg----" + msg);
System.out.println("获取status----" + status);
System.out.println("获取data----" + jsonData);
System.out.println("获取data里的city----" + city);
System.out.println("获取pm25----" + pm25);
System.out.println("获取pm25里的updateTime----" + updateTime);
System.out.println("获取data里的daily----" + jsonDaily);
System.out.println("获取data里的daily的第一组数据----" + jsonDailyFirst);
System.out.println("获取data里的daily的第一组数据的date----" + date);
//断言
Assert.assertEquals(msg, "ok");
} catch (Exception e) {
e.printStackTrace();
}
}
}
欢迎关注微信公众号:软件测试汪。软件测试交流群:809111560
转载请注意出处,谢谢合作