简体   繁体   中英

Access Json “nicely” from groovy templates

I have a groovy template that receives a JsonArray (gson) from the controller. What I want to do is to generate some HTML filled with some of the information from the JsonObjects contained in that array. Something like this (simplified for clarity):

<ul>
#{list items: sections, as:'section'}
   <li>${section.getAsJsonObject().get("title").getAsString()}
    <ul>
    #{list items: section.getAsJsonObject().getAsJsonArray("articles"), as:'article'}
        <li><a href="${article.getAsJsonObject().get("url").getAsString()}">${article.getAsJsonObject().get("title").getAsString()}</a></li>
    #{/list}
    </ul>
   </li>
#{/list}
</ul>

I find it very inconvenient to have to do the whole getAsJsonWhatever() all the time. Do you know of an alternative?

Please bear in mind that the following are not the answers I'm looking for:

  • send the json to the client and do it with javascript
  • do it with code in the controller
  • do it with code inside %{ }% tags
  • convert the json object to a java object in the controller and pass this to the template (this is my favourite alternative though)

EDIT: Solution

This is how things end up looking after applying Seb's solution:

controller:

Object json = slurper.parseText(response.getString());
render(json);

template:

<ul>
#{list items: json.data.publication.sections, as:'section'}
   <li>${section.title}
    <ul>
    #{list items: section.articles, as:'article'}
        <li><a href="${article.url}">${article.title}</a></li>
    #{/list}
    </ul>
   </li>
#{/list}
</ul>

I guess you get your json from a WS call.

Instead of converting the result of your json with default WS methods, you can get your result as a String and use groovy.json.JsonSlurper.parseText method to get a groovy object that you can use as a standard object in your groovy template.

Here is what I do in one of my templates

%{
def slurper = new groovy.json.JsonSlurper()
def jsonResult = slurper.parseText(response.getString())

if (jsonResult.success) {
    ...
}
}%

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM