使用render方法输出XML
Grails支持一些不同的方法来产生XML和JSON响应。第一个是隐式的通过render方法。
render方法可以传递一个代码块来执行标记生成器产生XML 
def list = {
def results = Book.list()
render(contentType:"text/xml") {
books {
for(b in results) {
book(title:b.title)
}
}
}
}
 
这段代码的结果将会像这样: 
<books>
<book title="The Stand" />
<book title="The Shining" />
</books>
 
注意,当你使用标记生成器时,必须小心避免命名冲突。例如,这段代码将产生一个错误: 
def list = {
def books = Book.list()  // naming conflict here
render(contentType:"text/xml") {
books {
for(b in results) {
book(title:b.title)
}
}
}
}
 
原因是,这里的一个本地变量books企图作为方法被调用。
使用render方法输出JSON
render 方法可以同样被用于输出JSON: 
def list = {
def results = Book.list()
render(contentType:"text/json") {
books {
for(b in results) {
book(title:b.title)
}
}
}
}
 
在这种情况下,结果就会是大致相同的: 
[
{title:"The Stand"},
{title:"The Shining"}
]
 
同样的命名冲突危险适用于JSON生成器。
自动XML列集(Marshalling)
(译者注:在此附上对于列集(Marshalling)解释:对函数参数进行打包处理得过程,因为指针等数据,必须通过一定得转换,才能被另一组件所理解。可以说列集(Marshalling)是一种数据格式的转换方法。)
Grails同样支持自动列集(Marshalling)领域类为XML通过特定的转换器。
首先,导入grails.converters 类包到你的控制器(Controllers)中: 
import grails.converters.*
 
现在,你可以使用下列高度易读的语法来自动转换领域类成XML: 
render Book.list() as XML
 
输出结果看上去会像下列这样: 
<?xml version="1.0" encoding="ISO-8859-1"?>
<list>
<book id="1">
<author>Stephen King</author>
<title>The Stand</title>
</book>
<book id="2">
<author>Stephen King</author>
<title>The Shining</title>
</book>
</list>
 
一个使用转换器的替代方法是使用Grails的codecs特性。codecs特性提供了encodeAsXML和encodeAsJSON方法: 
def xml = Book.list().encodeAsXML()
render xml
 
 
自动JSON列集(Marshalling)
Grails同样支持自动列集(Marshalling)为JSON通过同样的机制。简单替代XML 为JSON 
render Book.list() as JSON
 
输出结果看上去会像下列这样: 
[
{"id":1,
"class":"Book",
"author":"Stephen King",
"title":"The Stand"},
{"id":2,
"class":"Book",
"author":"Stephen King",
"releaseDate":new Date(1194127343161),
"title":"The Shining"}
]
 
再次作为一种替代,你可以使用encodeAsJSON达到相同的效果 
	posted on 2008-06-05 16:21 
周锐 阅读(587) 
评论(0)  编辑  收藏  所属分类: 
Groovy&Grails 、
Java 、
JavaScript 、
XML