日期:2014-05-16  浏览次数:20355 次

groovy JsonBuilder将对象转为json

?JsonBuilder将对象动态转为json

?

代码如下:

?

import groovy.json.*

?

def builder = new JsonBuilder()
?
??? ??? def root = builder{
??? ??? ??? "data"(
??? ??? ??? ??? LkInfo.list().collect{ lkInfo ->
??? ??? ??? ??? [
??? ??? ??? ??? ??? "city":lkInfo.city,
??? ??? ??? ??? ??? "name":lkInfo.name
??? ??? ??? ??? ??? ]
??? ??? ??? ??? }
??? ??? ??? )
??? ??? }

?

println? builder.toPrettyString();

?

结果如下:

?

{
??? "data": [
??????? {
??????????? "city": "太原",
??????????? "name": "名称1"
??????? },
??????? {
??????????? "city": "太原",
??????????? "name": "名称2"
??????? }

?? ]

}

?

?


??? ???