I am kinda new to Rest assured testing, I have been dealing with diff. json and Api's. I know how to pass a json object as body for POST request but my code gives error when I try to pass a JSON Array as body for POST request can someone suggest me how to do it.
The code I have been using for json object is
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);
This code gives class cast exception at jsonObject = (JSONObject) obj; when I pass a json array.
Kindly help me with the same This is the JSON Array
[
{
"findingId": "20177044",
"unsupressAfterDuration": 1669968369043,
"developer": "[email protected]",
"kbIds": [],
"ticketConfigurationId": "3350",
"customFields": []
}
]
CodePudding user response:
Your parser parses the part of JSON and probably returns a JSONArray, but you are casting it to JSONObject. Maybe you want to use something like
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
}
If you want only one code fragment to handle both objects and lists, cast to JsonStructure.
CodePudding user response:
answering my own question as I found a solution
JSONArray array1 = new JSONArray();
data1.put("findingId", findingIdFinal);
data1.put("unsupressAfterDuration", "1669968369043");
data1.put("developer","[email protected]");
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);