在groovy1.8中内置了对json格式数据的至此;
使对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'
本文介绍了 Groovy 1.8 如何内置 JSON 支持,提供简洁便利的 JSON 操作方式。通过构建 JSON 对象、映射数据到 JSON 和解析 JSON 字符串,实现灵活的数据交互。

4573

被折叠的 条评论
为什么被折叠?



