[英]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: 并希望将其呈现为XML / JSON,最好使用此方法:
render Book.list() as XML
However, I only want to render specific fields of that list, let's say: field1
, field2
, field3
. 但是,我只想渲染该列表的特定字段,例如: 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
. 如果要对XML输出进行严密控制,则应使用Grails的XMLBUilder而不是as XML
。 Here's an example that shows how to render an object using JSONBuilder, excluding properties such as class
, metaClass
, etc. 这是一个示例 ,演示如何使用JSONBuilder呈现对象,不包括class
, metaClass
等属性。
To only modification this example needs to generate XML instead of JSON is to instantiate a XMLBuilder
instead of a JSONBuilder
. 要仅修改此示例,需要生成XML而不是JSON,以实例化XMLBuilder
而不是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. 使用构建器(来自Don的答案)也是一个很好的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.