首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在部分JSON上使用JSONAssert与RESTAssured

在部分JSON上使用JSONAssert与RESTAssured
EN

Stack Overflow用户
提问于 2018-06-25 02:43:02
回答 1查看 1.7K关注 0票数 0

我能够使用RESTAssured从服务中检索JSON。

我想使用JSONPath功能提取JSON,然后使用JSONAssert对其进行比较。

下面是我的例子:

代码语言:javascript
复制
@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?

在代码示例中:

代码语言:javascript
复制
Object data = response.then().extract().path("data");

这将返回一个java.util.ArrayList。如何与JSONAssert一起使用它来与预期的JSON进行比较?

方法2-用JSONParser解析提取的数据

如果执行data.toString(),它将返回一个由于缺少对带有空格字符串的字符串值的引号处理而无法解析的字符串:

代码语言:javascript
复制
String dataString = response.then().extract().path("data").toString();
JSONArray dataArray = (JSONArray) JSONParser.parseJSON(dataString);

结果:

代码语言:javascript
复制
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属性?

谢谢;

EN

回答 1

Stack Overflow用户

发布于 2018-06-25 09:11:49

您可以在响应对象中使用jsonPath方法。

示例:

代码语言:javascript
复制
// this will return bar as per your example response.
String foo = response.jsonPath ().getString ("data[0].foo"); 

有关JSon路径的更多信息,请检查这里

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51015677

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档