霍格沃兹测试开发学社
ceshiren.com
是 JavaScript Object Notation 的缩写
是一种轻量级的数据交换格式
是理想的接口数据交换语言
官网:https://www.json.org/json-en.html
{
"args": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip,deflate",
"Hello": "Hogwarts",
"Host": "httpbin.ceshiren.com",
"User-Agent": "Apache-HttpClient/4.5.13 (Java/11.0.13)",
"X-Forwarded-Host": "httpbin.ceshiren.com",
"X-Scheme": "https"
},
"origin": "113.89.246.226",
"url": "https://httpbin.ceshiren.com/get"
}
项目地址:https://github.com/json-path/JsonPath
JSONPath | 描述 |
---|---|
$ |
根节点 |
@ |
现行节点 |
.. |
不管位置,选择所有符合条件的元素 |
* |
匹配所有元素节点 |
. |
取子节点 |
[] |
取子节点,支持名称或者下标 |
[,] |
支持迭代器中做多选 |
?() |
支持过滤操作 |
$.address.city
$.phoneNumbers[0].number
$.phoneNumbers[*].number
$..number
$[address][city]
$[phoneNumbers][0][number]
$.phoneNumbers[?(@.type == 'iPhone')].number
REST assured
内置解析方法json-path
解析方法import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static io.restassured.path.json.JsonPath.from;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestJSONPathNested {
@Test
void fun() {
// 获取响应信息,并转成字符串对象
String resp = given()
.header("Hello", "Hogwarts")
.when()
.get("https://httpbin.ceshiren.com/get")
.then()
.log().body()
.extract().response().asString();
// 使用JSONPath解析响应体
String word = from(resp).getString("headers.Hello");
System.out.println(word);
// 响应断言
assertEquals("Hogwarts", word);
}
}
package ch06;
import com.jayway.jsonpath.JsonPath;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestJSONPathStandalone {
@Test
void fun() {
// 获取响应信息,并转成字符串对象
String resp = given()
.header("Hello", "Hogwarts")
.when()
.get("https://httpbin.ceshiren.com/get")
.then()
.extract().response().asString();
// 使用JSONPath解析响应体
String word = JsonPath.read(resp, "$.headers.Hello");
System.out.println(word);
// 响应断言
assertEquals("Hogwarts", word);
}
}
JSONPath
依赖配置pom.xml
中添加配置信息