Groovy对Json的常见处理

阅读更多
1、JsonBuilder构建

示例1,

people = new Expando(name:"ZJ", addr:"ShangHai")
people.phone = [131111111, 132111111] // List
people.expr = [java:2, groovy:1] // Map

builder = new groovy.json.JsonBuilder(people)
writer = new StringWriter()
builder.writeTo(writer)

println writer


返回结果
{
"name":"ZJ",
"addr":"ShangHai",
"phone":[131111111,132111111],
"expr":{
"java":2,
"groovy":1
}
}

===================================================================

示例2,

def builder = new JsonBuilder()
//如同构建对象一样
builder.pepole{
person{
firstName 'lu'
lastName 'zhang'
//传入map
address(
city: 'Shanghai',
country: 'China',
zip: 12345,
)
married false
//传如list
conferences 'sftp', 'windows'
}
}
//以树形结构输出
println JsonOutput.prettyPrint(builder.toString())

运行结果
{
    "pepole": {
        "person": {
            "firstName": "lu",
            "lastName": "zhang",
            "address": {
                "city": "Shanghai",
                "country": "China",
                "zip": 12345
            },
            "married": false,
            "conferences": [
                "sftp",
                "windows"
            ]
        }
    }
}




2、JsonBuilder定制化构建

array = [131111111,132111111]
exp = [java:2, groovy:1]
builder = new groovy.json.JsonBuilder()
builder {
name "ZJ"
addr "ShangHai"
phone array
expr exp
}
writer = new StringWriter()
builder.writeTo(writer)

println writer

返回结果
{
    "name": "ZJ",
    "addr": "ShangHai",
    "phone": [
        131111111,
        132111111
    ],
    "expr": {
        "java": 2,
        "groovy": 1
    }
}


3、JsonSlurper解析

示例1,
jsonText1 = """{
"name":"ZJ",
"addr":"ShangHai",
"phone":[131111111,132111111],
"expr":{
"java":2,
"groovy":1
}
}"""

slurper = new groovy.json.JsonSlurper()
people = slurper.parseText(jsonText1)
//people = slurper.parse(new FileReader('person.json'))
println people.name // ZJ
println people.addr // ShangHai
println people.phone // [131111111, 132111111]
println people.expr // [groovy:1, java:2]


示例2,
jsonText2 = """
{
    "pepole": {
        "person": {
            "firstName": "lu",
            "lastName": "zhang",
            "address": {
                "city": "Shanghai",
                "country": "China",
                "zip": 12345
            },
            "married": false,
            "conferences": [
                "sftp",
                "windows"
            ]
        }
    }
}
"""

//类似XmlSlurper
def root = new JsonSlurper().parseText(jsonText2)
assert root instanceof Map
assert root.person.conferences instanceof List
assert root.person.firtsName == 'lu'
assert root.person.conferences[1] == 'windows'

你可能感兴趣的:(groovy)