繁体   English   中英

在 POST 请求中将数组作为 BODY 传递

[英]Passing Array as a BODY in a POST request

我对 Rest 保证测试有点陌生,我一直在处理差异。 json 和 Api 的。 我知道如何将 json object 作为 POST 请求的正文传递,但是当我尝试将 JSON 数组作为 POST 请求的正文传递时,我的代码出错,有人可以建议我如何去做。

我一直在使用 json object 的代码是

 obj = parser.parse(new FileReader("path of json"));
        jsonObject = (JSONObject) obj;
        String jsonString = jsonObject.toJSONString();
        Map<String, String> body = new ObjectMapper().readValue(jsonString, HashMap.class);
        response = RestAssuredExtension.PostOpsWithBody(url, body);

此代码在 jsonObject = (JSONObject) obj 处给出 class 强制转换异常; 当我传递一个 json 数组时。

请帮助我,这是 JSON 数组

[
    {
    "findingId": "20177044",
    "unsupressAfterDuration": 1669968369043,
    "developer": "manan.girdhar@armorcode.io",
    "kbIds": [],
    "ticketConfigurationId": "3350",
    "customFields": []
  }
]

您的解析器解析 JSON 的部分并可能返回一个 JSONArray,但您正在将其转换为 JSONObject。 也许您想使用类似的东西

obj = parser.parse(new FileReader("path of json"));
if (obj instanceof JSONObject) {
    jsonObject = (JSONObject) obj;
    String jsonString = jsonObject.toJSONString();
    Map<String, String> body = new ObjectMapper().readValue(jsonString, HashMap.class);
    response = RestAssuredExtension.PostOpsWithBody(url, body);
} else {
    throw new Exception("We do not know how to handle non-objects like " + obj.getClass().getName());
    // replace this with list-handling code
}

如果您只需要一个代码片段来处理对象和列表,请强制转换为JsonStructure

在找到解决方案时回答我自己的问题

JSONArray array1 = new JSONArray();
        data1.put("findingId", findingIdFinal);
         data1.put("unsupressAfterDuration", "1669968369043");
         data1.put("developer","manan.girdhar@armorcode.io");
         data1.put("kbIds",array1);
         data1.put("ticketConfigurationId", jiraId);
         data1.put("customFields",array1);
        array.put(data1);
        String jsonString = array.toString();
        List<Map<String, String>> body = new ObjectMapper().readValue(jsonString, List.class);
        response = RestAssuredExtension.PostOpsWithBodyWithArray(url, body);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM