Search code examples
grailsgrails3

Name value pairs in Grails Views


I have a Header class like so:

class Header {
  String name
  String value
}

I have a Grails View like this:

model {
  Set<Header> headers
}

json {
  headers ....
}

I want to produce JSON formatted like this:

{
  "headers": {
    "Host": "xyz.com",
    "Other-Header": "da value"
  }
}

I tried generating the JSON value by hand, but Grails just put it inside quotes. So that didn't work.


Solution

  • Convert the Set<Header> to a Map<String, String> first:

    model {
        Set<Header> headers
    }
    
    json {
        headers renderHeaders(email.headers)
    }
    
    static Map<String, String> renderHeaders(Set<Header> headers) {
        Map<String, String> res = [:]
        for (Header header : headers) {
            res[header.name] = header.value
        }
        return res
    }