I have this method which creates a map from a JSON request parameter. Right now I've hard-coded JSON keys to convert it to map. Can it be converted to a generic method which converts a request's JSON object to a map?


Content-Disposition: form-data; name="invoice_903"

Groovy method:

def getRequestParameterMap(def request) {
        def params = request.getParameterNames()
        def requestParamMap = [:]
        while (params.hasMoreElements()) {
            String fieldName = (String) params.nextElement();
            if (fieldName.startsWith("invoice_")) {
                JSONObject obj = JSONUtil.parseJSONObject(request.getParameter(fieldName));
                def id = obj.get("id").toString()
                def parcelId = obj.get("parcelId").toString()
                def referenceId = obj.get("referenceId").toString()
                requestParamMap["id"] = id
                requestParamMap["parcelId"] = parcelId
                requestParamMap["referenceId"] = referenceId

In order to convert String to Map, use JsonSlurper:

new JsonSlurper().parseText(requestString)
  • \$\begingroup\$ Thanks, it worked, just wondering can the method be optimized anymore further? \$\endgroup\$ – RanPaul May 11 '17 at 16:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.