简体   繁体   中英

Grails render lists

I have a list like this:

 def bookList = Book.list()

and want to render it as XML/JSON, preferably using this approach:

render Book.list() as XML

However, I only want to render specific fields of that list, let's say: field1 , field2 , field3 . The other useless stuff won't be shown.

If you want close control over the XML output you should use Grails' XMLBUilder instead of as XML . Here's an example that shows how to render an object using JSONBuilder, excluding properties such as class , metaClass , etc.

To only modification this example needs to generate XML instead of JSON is to instantiate a XMLBuilder instead of a JSONBuilder .

If your case is simple enough, you could just collect what you need, eg:

def output = Book.list().collect { [
    field1: it.field1,
    field2: it.field2,
    field3: it.field3
] }

render output as XML

Using a builder (from Don's answer) is an excellent solution as well.

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