Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails : How to access the params coming as JSON format

from PHP application there is call to grails controller which sends data in JSON format.

when i println the params

println params 

which prints

[{"courseCategory":null,"courseId":null,"show":null,
    "rows":6,"trainers":null,"courses":null,"cities":null,
    "fromDate":null,"toDate":null,"pageType":"HOME","deal":null}:,   
    action:getTrainingsAsJson, 
    controller:publicTraining]

when i do

println  params.rows
println params.pageType

which prints null

i tried

  def jsonObject = request.JSON  // prints [:]

I have also tried with JsonSlurper

def slurper = new JsonSlurper()
def result = slurper.parseText(params)

which gives error

No signature of method: groovy.json.JsonSlurper.parseText() is applicable for argument types: (org.codehaus.groovy.grails.web.servlet.mvc.GrailsParameterMap)

how to convert it to retrieve the param values?

or is there any way to convert it to map so that i can easily access the parameters?

like image 316
monda Avatar asked Oct 03 '13 13:10

monda


3 Answers

If it is a POST request then the JSON can be retrieved from request as

request.JSON
request.JSON.courseCategory

etc

What is see from the request the values are sent null from the client. Verify the payload.

like image 196
dmahapatro Avatar answered Nov 15 '22 17:11

dmahapatro


[{"courseCategory":null,...,"deal":null}:, action:getTrainingsAsJson,  controller:publicTraining]

It looks like you are sending your data without key, like

data: JSON.stringify({"courseCategory":null,...,"deal":null}),

send it with some key like

jQuery.ajax({
    url: '${g.createLink(action: 'asd')}',
    type: 'post',
    dataType: 'json',
    data: "sendData=" + JSON.stringify({"courseCategory":null,"courseId":null,"show":null, "rows":6,"trainers":null,"courses":null,"cities":null, "fromDate":null,"toDate":null,"pageType":"HOME","deal":null}),
    success: function (data) {
        console.debug(data);
    }
});

and then get value like

def data = JSON.parse(params.sendData)
def rows = data.rows

Try this..,.

like image 42
MKB Avatar answered Nov 15 '22 19:11

MKB


In case anyone is running into an issue with calling request.JSON and receiving null -- be sure that you explicitly set the dataType and contentType, and send the data as JSON. For example, using jQuery:

$.ajax({
    url: yourURL,
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    data: JSON.stringify(yourJsonObject)
});
like image 29
Igor Avatar answered Nov 15 '22 19:11

Igor