Groovy optimize method to convert JSON to map

Posted on


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)

Leave a Reply

Your email address will not be published. Required fields are marked *