首页 > 解决方案 > 如何从 Json 响应中提取特定值并在 Rest Assured Automation Testing 的输入负载 json 文件中使用该值

问题描述

我没有使用任何 POJO 类。相反,我使用外部 json 文件作为我的 2 个 API(获取 API 和删除 API)的有效负载文件。

添加 API >> 添加书名、书架、其他书籍详细信息以及唯一的 place_id。删除 API >> 用于使用上面唯一的 place_id 从特定机架中删除一本书。

由于我使用的是外部 json 有效负载输入文件,请告诉我如何传递从 GET API 获取的“place_id”并将此 place_id 发送到 DELETE API 外部 json 文件然后使用它

在下方添加 Place API:此 API 在响应中返回唯一的 Place_ID

{
  "location": {
    "lat": -38.383494,
    "lng": 33.427362
  },
  "accuracy": 50,
  "name": "Frontline house 1",
  "phone_number": "(+91) 983 893 3937",
  "address": "2951, side layout, cohen 09",
  "types": [
    "shoe park",
    "shop"
  ],
  "website": "http://google.com",
  "language": "French-IN"
}

删除下面的地方 API

{
  "place_id": "<need to insert place_id from above response>"
}

标签: apiweb-servicesautomationrest-assuredrest-assured-jsonpath

解决方案


您可以使用 java 中的 json-simple 库来执行此操作。json-简单的maven仓库

进口

import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import org.json.simple.JSONObject
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

您必须达到以下要求;

  1. 从 Add Place API json 响应中检索 place_id

  2. 从 json 文件中读取 Delete Place API 的请求正文

  3. 替换 Delete Place API 请求正文中的 place_id 值

  4. 将新的请求正文写入 Delete Place API json 文件

    // Retrieve place_id from Add Place API json response
    Response response = RestAssured
            .when()
            .get("add_place_api_url")
            .then()
            .extract()
            .response();
    
    JsonPath jsonPath = response.jsonPath();
    
    String placeId = jsonPath.get("place_id");
    
    // Read request body of Delete Place API from json file
    JSONObject jsonObject = new JSONObject();
    JSONParser parser = new JSONParser();
    try {
        Object obj = parser.parse(new FileReader("path/DeletePlaceRequestBody.json"));
    
        jsonObject = (JSONObject) obj;
    
        // Replace the place_id value in request body of Delete Place API
        jsonObject.replace("place_id", placeId);
    
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    
    // Write the new request body to Delete Place API json file
    try {
        FileWriter file = new FileWriter("DeletePlaceRequestBody.json");
        file.write(jsonObject.toString());
    
        file.flush();
        file.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    

推荐阅读