簡體   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