1

I'm using Grails for my application, and I have a problem with JSON converters.

In my controller, I have:

def myObject = [:]
myObject.key = 'value'
render ???

what is optimal way to render myObject as JSON from the controller?

tim_yates
  • 167,322
  • 27
  • 342
  • 338
Valeriane
  • 936
  • 3
  • 16
  • 37
  • 1
    I assume `myObject` is a map? The code you posted makes no sense otherwise. If this is the case, instead of `myObject.put("key", "value")`, you can do: `myObject[ 'key' ] = 'value'` – tim_yates Jan 22 '13 at 11:19
  • 1
    Adding to tim's point. You can even do myObject.key = 'value' – uchamp Jan 22 '13 at 11:27
  • 1
    @Valeri Maybe that nugget of important information should be in the question? – tim_yates Jan 22 '13 at 11:30
  • Updated the question so it is more understandable, and includes @uchamp's suggestion – tim_yates Jan 22 '13 at 11:51

2 Answers2

10

It's easy :

render (myObject as JSON)

or

render ([key: "value"] as JSON)
  • 3
    `render myObject as JSON` would do, no need for the parentheses – tim_yates Jan 22 '13 at 12:01
  • 1
    Leaving out the parentheses is fine for simple cases, but it trips you up if you ever try to do `render (something) as JSON` (which parses as `(render something) as JSON` rather than `render (something as JSON)`). After having been bitten by this once too often I now use the explicit parentheses every time... – Ian Roberts Sep 23 '13 at 12:52
1

Other way is :

        render (contentType: 'text/json'){
        array {
            for(f in Person.list()){
                person id: f.id, name: f.name
            }
        }
    }

This sample render a list of Persons