json 在POST请求中将Array作为BODY传递

ioekq8ef  于 2022-11-19  发布在  其他
关注(0)|答案(2)|浏览(279)

我是一个新手,我一直在处理diff. json和Api的。我知道如何传递一个json对象作为POST请求的主体,但是当我尝试传递一个JSON数组作为POST请求的主体时,我的代码出错了,有人能建议我如何做吗?
我为json对象使用的代码是

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处给出类转换异常;当我传递一个json数组时。
这是JSON数组

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

toiithl61#

解析器解析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

u2nhd7ah

u2nhd7ah2#

回答我自己的问题,因为我找到了一个解决方案

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);

相关问题