例:
List<String> tests=new ArrayList<String>()
tests.add ('test1')
tests.add ('test2')
tests.add ('test3')
StringBuffer buf=new StringBuffer()
buf.append("{items:[")
int i=0
tests.each {
if(i>0){
println ","
}
buf.append("{test:")..append("'").append(it).append("'}")
i++
}
buf.append("]}")
以上是通过变量i来控制索引号的,以下可以直接利用
grails中遍历自带的方法获得索引:
List<String> tests=new ArrayList<String>()
tests.add ('test1')
tests.add ('test2')
tests.add ('test3')
StringBuffer buf=new StringBuffer()
buf.append("{items:[")
tests.eachWithIndex {
test,i->
if(i>0){
println ","
}
buf.append("{test:").append("'").append(test).append("'}")
}
buf.append("]}")