Grails Controller: Render String as JSON Response

controller, grails, json

Solution

If you already have the response in JSON format, you could render it directly.

response.setContentType("application/json")
render '[{"name":"Afghanistan","code":"AF"},{"name":"Aland Islands","code":"AX"},{"name":"Albania","code":"AL"}]'

Problem

I have a simple autocomplete text-input field on my GSP that gets its values (a list of countries) from a controller via AJAX request. All works fine if the controller looks like this: ``` def getAllCountries() { def countries = [[name: 'Afghanistan', code: 'AF'],[name: 'Åland Islands', code: 'AX'],[... render countries as JSON } ``` However, If would like to pass the countries within a string that already contains the countries in a json formatted way, so I can use different representations of the string for Internationalisaion, like this: ``` def countries = "[{'name':'Afghanistan', code: 'AF'},{'name':'Åland Islands', code: 'AX'},{'name':'Albania', code: 'AL'},{..." ``` However, now I receive a casting exception when I call render countries as JSON. Is there any way I can pass the String directly to the view? Thank you very much in adavance.

Original source