3
\$\begingroup\$

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?

Request:

Content-Disposition: form-data; name="invoice_903"
{"id":"903","parcelId":18,"referenceId":"T44428"}`

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
            }
        }
        requestParamMap
    }
\$\endgroup\$

1 Answer 1

7
\$\begingroup\$

In order to convert String to Map, use JsonSlurper:

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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.