3
votes

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.

3

3 Answers

13
votes

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"}]'
3
votes

The render method accepts text as parameter as well:

render contentType: "text/json", text: '[{"name":"Afghanistan" ...}]'
2
votes

Rendering [[name: 'Afghanistan', code: 'AF']] as JSON will result as [{"name":"Afghanistan","code":"AF"}], and it doesn't make sense to try convert already json formatted String to JSON.
If you have "[{'name':'Afghanistan', code: 'AF'}]", just use it without converting to Json.