sargas sargas - 2 months ago 7
JSON Question

How to render arbitrary JSON with the correct content type in Grails?

I'm trying to output something simple like

{"error": "endpoint not available"}


The snippet below renders with content type text/html:

render ([error: 'endpoint not available']) as JSON


And I've also tried:

render(contentType: 'application/json') {
error {
"endpoint not available"
}
}


Which I know it doesn't produce the desired JSON.

How can I produce the JSON I want with the application/json content type?

Answer

Try:

def responseData = [
    'error': 'endpoint not available'
]
render responseData as JSON