我能够使用RESTAssured从服务中检索JSON。
我想使用JSONPath功能提取JSON,然后使用JSONAssert对其进行比较。
下面是我的例子:
@Test
public void doAPITestExample() throws JSONException {
// retrieve JSON from service
Response response = RestAssured.given().get("http://localhost:8081/mockservice");
response.then().assertThat().statusCode(200);
String body = response.getBody().asString();
System.out.println("Body:" + body);
/*
{"datetime": "2018-06-21 17:48:07.488384", "data": [{"foo": "bar"}, {"test": "this is test data"}]}
*/
// able to compare entire body with JSONAssert, strict=false
Object data = response.then().extract().path("data");
System.out.println("Response data:");
System.out.println(data.getClass()); // class java.util.ArrayList
System.out.println(data.toString());
// JSONAssert data with strict=false
String expectedJSON = "{\"data\":[{\"foo\": \"bar\"}, {\"test\": \"this is test data\"}]}";
JSONAssert.assertEquals(expectedJSON, response.getBody().asString(), false);
// How do I extract JSON with JSONPath, use JSONAssert together?
}方法1-使用JSONPath获取JSONObject
如何让JSONPath返回可由JSONAssert使用的JSONObject?
在代码示例中:
Object data = response.then().extract().path("data");这将返回一个java.util.ArrayList。如何与JSONAssert一起使用它来与预期的JSON进行比较?
方法2-用JSONParser解析提取的数据
如果执行data.toString(),它将返回一个由于缺少对带有空格字符串的字符串值的引号处理而无法解析的字符串:
String dataString = response.then().extract().path("data").toString();
JSONArray dataArray = (JSONArray) JSONParser.parseJSON(dataString);结果:
org.json.JSONException: Unterminated object at character 24 of [{foo=bar}, {test=this is test data}]方法3-使用JSON模式验证
是否可以仅从JSON中提取data属性并在该部分上针对JSON运行该属性?
注意:返回的整个JSON相当大。我只想验证它的data属性。
执行JSON模式验证的示例将只查找JSON中的data属性?
谢谢;
发布于 2018-06-25 09:11:49
您可以在响应对象中使用jsonPath方法。
示例:
// this will return bar as per your example response.
String foo = response.jsonPath ().getString ("data[0].foo"); 有关JSon路径的更多信息,请检查这里。
https://stackoverflow.com/questions/51015677
复制相似问题