How to get at JSON in grails 2.0

Posted by Mikey on Stack Overflow See other posts from Stack Overflow or by Mikey
Published on 2012-03-25T20:42:52Z Indexed on 2012/03/26 23:29 UTC
Read the original article Hit count: 221

Filed under:
|
|
|

I am sending myself JSON like so with jQuery:

$.ajax
({
  type: "POST",
  url: 'http://localhost:8080/myproject/myController/myAction',
  dataType: 'json',
  async: false,
  //json object to sent to the authentication url
  data: {"stuff":"yes",
         "listThing":[1,2,3],
         "listObjects":[{"one":"thing"},{"two":"thing2"}]},
  success: function () {
    alert("Thanks!"); 
  }
})

I send this to a controller and do

println params

And I know I'm already in trouble...

[stuff:yes, listObjects[1][two]:thing2, listObjects[0][one]:thing, listThing[]:[1, 2, 3], action:myAction, controller:myController]

I cannot figure out how to get at most of these values...

I can get "yes" with params.stuff, but I cant do params.listThing.each{} or params.listObjects.each{}

What am I doing wrong?

UPDATE:

I make the controller do this to try the two suggestions so far:

println params
println params.stuff
println params.list('listObjects')
println params.listThing
def thisWontWork = JSON.parse(params.listThing)
render("omg l2json")

look how weird the parameters look at the end of the null pointer exception when I try the answers:

[stuff:yes, listObjects[1][two]:thing2, listObjects[0][one]:thing, listThing[]:[1, 2, 3], action:l2json, controller:rateAPI]
yes
[]
null
| Error 2012-03-25 22:16:13,950 ["http-bio-8080"-exec-7] ERROR   errors.GrailsExceptionResolver  - NullPointerException occurred when processing request: [POST] /myproject/myController/myAction - parameters:
stuff: yes
listObjects[1][two]: thing2
listObjects[0][one]: thing
listThing[]: 1
listThing[]: 2
listThing[]: 3

UPDATE 2 I am learning things, but this can't be right:

println params['listThing[]']
println params['listObjects[0][one]']

prints

[1, 2, 3]
thing

It seems like this is some part of grails new JSON marshaling. This is somewhat inconvenient for my purposes of hacking around with the values. How would I get all these individual params back into a big groovy object of nested maps and lists?

Maybe I am not doing what I want with jQuery?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about AJAX