Groovy操作json

1248 ワード

groovy 1.8にはjson形式のデータが内蔵されている.
jsonの操作を非常に簡素で便利にしました
def builder = new JsonBuilder()
//       
builder.pepole{
	person {
		firstName 'leng'
		lastName 'feng'
		//  map
		address(
				city: 'Shanghai',
				country: 'China',
				zip: 12345,
				)
		married true
		//  list
		conferences 'JavaOne', 'Gr8conf'
	}
}
//       
println JsonOutput.prettyPrint(builder.toString())




String json = """
{
    "pepole": {
        "person": {
            "firstName": "leng",
            "lastName": "feng",
            "address": {
                "city": "Shanghai",
                "country": "China",
                "zip": 12345
            },
            "married": true,
            "conferences": [
                "JavaOne",
                "Gr8conf"
            ]
        }
    }
}
"""
//  XmlSlurper
def root = new JsonSlurper().parseText(json)
assert root instanceof Map
assert root.person.conferences instanceof List
assert root.person.firtsName == 'leng'
assert root.person.conferences[1] == 'Gr8conf'