Shenoy Tinny Shenoy Tinny - 3 months ago 78x
JSON Question

Render in CSV format in grails

Grails provides Converter class to quickly transform any kind of Java/Groovy objects to either XML/JSON response.

render obj as XML


render obj as JSON

I am working on a grails app that requires me to render an object in csv format. Is there a way to do that?

I tried out few stuff and I have explained those below:

Snippet of my code

csv {
def results = []
for(d in Data.list()) {
def r= [,]
results << r
def result = ''
results.each{ row ->
col -> result += col + ','
result = result[0..-2]
result += '\n'
println result


I stored my results in an ArrayList and then converted them to a comma separated string and then passed it to a render method. When I run the above code on the browser, it creates the desired file and the browser pops up a dialog box to "Save As" the file.

When I changed the contentType to text/html, the file contents are displayed on the browser with no newline chars.

Is there a better way to render the contents of the csv file on the browser the same way its on the file.



You can render the CSV as text/plain instead of text/html. Browsers will render this as plain text, similar to what you'd see if you open the file in an editor.