WebServices Before Operation Rule Returns error on JsonUtil.toMap(<String>)

I need a WS Before Operation Rule to fetch a value and then add that to the body for the existing request generated. Initially I am hardcoding the value to feed into the body but getting the following error on the JsonUtil.toMap method
java.lang.RuntimeException: Source JSON is not a Map. class java.util.ArrayList cannot be cast to class java.util.Map (java.util.ArrayList and java.util.Map are in module java.base of loader ‘bootstrap’)

I am using the code from the Developer documentation example rule.

Map body = requestEndPoint.getBody(); returns
{jsonBody=[{"FirstName":"John","SourceUniqueID":"3A60703E-5030-46B6-BC01-66C0AC6E63E7","ClientUniqueID":"D1040852-AF23-4AA3-B7D6-6DD7197B68CF"}], bodyFormat=raw}

String jsonBody = (String) body.get("jsonBody"); returns
[{"FirstName":"John","SourceUniqueID":"3A60703E-5030-46B6-BC01-66C0AC6E63E7","ClientUniqueID":"D1040852-AF23-4AA3-B7D6-6DD7197B68CF"}]

But when the following line executes
Map jsonMap = JsonUtil.toMap(jsonBody); I get the error

Even though jsonBody is declared as a String, its format seems to be causing it to be handled as an ArrayList? If that is the case, I am not sure how to prevent that. Thanks

The json body is a list. Try jsonBody[0] to grab the first object in the list.

Hi

You should parse it using JsonUtil.toList instead of JsonUtil.toMap

Thank you Sivakrishna, that did get me by that error. The complete snippet of code to retrieve the current jsonBody from the requestEndPoint and append to it with values derived in the Rule itself is below if anyone else runs into a similar issue

But I am curious why the code I had initially tried, since it is referenced in the documentation and in so many of the postings on the forums, was throwing the error for me. Wouldn’t the format of the jsonBody element retrieved from the requestEndPoint be the same for all scenarios and run into this issue?
[{“FirstName”:“John”,“SourceUniqueID”:“3A60703E-5030-46B6-BC01-66C0AC6E63E7”,“ClientUniqueID”:“D1040852-AF23-4AA3-B7D6-6DD7197B68CF”}]

Map body = requestEndPoint.getBody();
String jsonBody = (String) body.get("jsonBody");
List jsonList = JsonUtil.toList(jsonBody);
Map jsonListMap = jsonList.get(0);
jsonListMap.put("employeeID","f0b28861-8eae-4dd6-a074-9994bbb440e6");
String finalBody = JsonUtil.render(jsonList);
body.put("jsonBody", finalBody);
requestEndPoint.setBody(body);