roovy 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"
        }

   ]

}

 

代码2:

 import groovy.json.*

def ars=[["1":1,"2":2],"456","789"]
def builder = new JsonBuilder() 
//如同构建对象般 
builder.pepole{ 
    person { 
        firstName 'leng' 
        lastName 'feng' 
        //传入map 
        address1{
                city 'BeiJing' 
                country 'China' 
                zip 12345
                } 
        address2(
                city: 'Shanghai', 
                country: 'China', 
                zip: 12345
                ) 
        married true 
        //传如list 
        conferences 'JavaOne', 'Gr8conf' 
        delegate."ars"(ars)
    } 

//以树形结构输出 
println JsonOutput.prettyPrint(builder.toString()) 

输出:

 {
    "pepole": {
        "person": {
            "firstName": "leng",
            "lastName": "feng",
            "address1": {
                "city": "BeiJing",
                "country": "China",
                "zip": 12345
            },
            "address2": {
                "city": "Shanghai",
                "country": "China",
                "zip": 12345
            },
            "married": true,
            "conferences": [
                "JavaOne",
                "Gr8conf"
            ],
            "ars": [
                {
                    "1": 1,
                    "2": 2
                },
                "456",
                "789"
            ]
        }
    }
}