从Rest Assured Json响应中获取多个项目的随机字段

时间:2017-03-22 19:36:29

标签: java json rest-assured

从Ruby迁移到Java,我需要从多项响应中随机解析并获取一个字段。

这是我用来获取回复的ApiCall方法:

        Response response = given().
            headers(this.headers).
            params(this.body).
        when().
            post(this.url).
        then().
            contentType(ContentType.JSON).
            statusCode(200).
        extract().
            response();

它给了我这个JSON结构:

{
  "Contents": {
    "Title": "Search results",
    "Count": "10",
    "Page": "1",
    "TotalCount": "1",
    "TotalPages": 2,
    "Genres": [
      "Genre_1",
      "Genre_2",
      "Genre_3"
    ],
    "Contents": [
      {
        "title": "content1_title",
        "original_text": "original text 1",
        "full_text": "Sample full sized text 1",
        "short_text": "Sample short text 1",
        "children_ids": {
          "item": [
            1,
            2
          ]
        },
        "children_uuids": {
          "item": [
            "item1_uuid",
            "item2_uuid"
          ]
        },
        "parent_ids": {
          "item": [
            1
          ]
        },
        "parent_uuids": {
          "item": [
            "item1_uuid"
          ]
        },
        "aired_from": "1994-01-01",
        "aired_to": "1994-12-31",
        "tags": {
          "item": [
            ""
          ]
        },
        "available_condition1": 0,
        "available_condition2": 1,
        "price_condition1": "0.00",
        "price_condition2": "13.00"
      },
      {
        "title": "content2_title",
        "original_text": "original text 2",
        "full_text": "Sample full sized text 2",
        "short_text": "Sample short text 2",
        "children_ids": {
          "item": [
            1,
            2
          ]
        },
        "children_uuids": {
          "item": [
            "item1_uuid",
            "item2_uuid"
          ]
        },
        "parent_ids": {
          "item": [
            1
          ]
        },
        "parent_uuids": {
          "item": [
            "item1_uuid"
          ]
        },
        "aired_from": "1998-01-01",
        "aired_to": "1998-01-31",
        "tags": {
          "item": [
            ""
          ]
        },
        "available_condition1": 0,
        "available_condition2": 1,
        "price_condition1": "0.00",
        "price_condition2": "13.00"
      }
    ]
  },
  "Success": true
}

问题是我需要随机获得#34;标题"至少有一个" children_uuids"从响应中的总数来看。

据我了解,步骤如下:

1)得到" Contents.Contents"的总大小。项目。 2)获得0到项目总数之间的随机数。 3)使用该数字选择一个带有" Contents.Contents。[n] .title"格式或类似。

尝试以下操作但没有成功:

        JsonPath jsonPath = new JsonPath(response.toString());
        List<?> list = jsonPath.getList("Contents.Contents.title.flatten()");
        System.out.println(list);

这给了我以下错误:

io.restassured.path.json.exception.JsonPathException: Failed to parse the JSON document

作为参考,在Ruby中代码将是:

            amount = @result['api_response']['Contents']['Contents'].count
            amount = amount - 1
            a = rand(0..amount)
            while @result['api_response']['Contents']['Contents'][a]['children_uuids']['item'].nil? do
                a = rand(0..amount)
                #children_uuids = $result['api_response']['Contents']['Contents'][a]['children_uuids']
            end
            #price_hd = @result['api_response']['Contents']['Contents'][a]['price_hd']
            content_title = @result['api_response']['Contents']['Contents'][a]['title']

更新:我已经让它部分工作了...我已经找到了一种方法从列表中选择一个项目:

String contentTitle = response.then().extract().path("Contents.Contents[0].title");

但是找不到使用这个jsonpath的方法

String contentTitle = response.then().extract().path("Contents.Contents.[?(@.children_uuids)].uuid");

第二行给了我:

java.lang.IllegalArgumentException:
Invalid JSON expression:
Script1.groovy: 1: unexpected token: [ @ line 1, column 45.
   nRootObject.Contents.Contents.[?(@.child
                                 ^

提前致谢。

2 个答案:

答案 0 :(得分:0)

在我看来,这在REST保证中很难做到,甚至可能是Java。

我建议你看看Karate(免责声明:我是开发者)。因此,您可以调用JavaScript函数来生成随机数,将其分配给变量,然后形成路径表达式以完全按照您的意愿执行:

Feature:

Scenario:

* def data = read('data.json')
* def size = (data.Contents.Contents.length)
* def index = Math.floor(Math.random() * size)
* print 'selected index: ' + index
* def item = (data.Contents.Contents[index])
* def children_uuids = item.children_uuids
* match children_uuids == { item: ['item1_uuid', 'item2_uuid'] }

答案 1 :(得分:0)

更新:我找到了一个包含以下代码的解决方案:

            // get random content data
            Integer contentAmmount = response.body().path("Contents.Contents.size()");
            Random randomGenerator = new Random();
            int randomInt = randomGenerator.nextInt(contentAmmount);
            while (response.body().path(
                    String.join("", "Contents.Contents[", Integer.toString(randomInt), 
                            "].children_uuids.item")).toString().isEmpty() ) {
                randomInt = randomGenerator.nextInt(contentAmmount);
            }

            String contentTitle = response.then().extract()
                    .path(String.join("", "Contents.Contents[", Integer.toString(randomInt), "].title"));
            String contentUuid = response.then().extract()
                    .path(String.join("", "Contents.Contents[", Integer.toString(randomInt), "].uuid"));
            String contentChildrenUuid = response.body().path(
                    String.join("", "Contents.Contents[", Integer.toString(randomInt), 
                            "].children_uuids.item"));