Groovy 操作json

在groovy1.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'


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章