Groovy中json的一些操作

在测试过程中,尤其是接口自动化测试框架搭建时,经常会碰到 json 文件或者数据流的处理,下面看看json的一些处理实例:

/**
 * @author :ZackZhou
 * @date :Created in 2020/9/7 5:49 PM
 * @description :Groovy Json 的一些操作
 * @modified By:
 * @version:
 */

import groovy.json.JsonBuilder
import groovy.json.JsonOutput
import groovy.json.JsonSlurper

def dids = ["1","2"]
def gids =["1","2"]

def did_content = new ArrayList<Map>()
def gid_content = new ArrayList<Map>()

for(did in dids)
{
    def single = [:]
    single.put("deviceId","${did}")
    single.put("deviceSeri","")
    single.put("deviceType","")

    did_content.add(single)
}

for(gid in gids)
{
    def single = [:]
    single.put("targetValue","${gid}")
    single.put("operator","2")
    single.put("classId","0")
    single.put("targetId","0")

    gid_content.add(single)
}

def did_json = new File("./did.json")
def gid_json = new File("./gid.json")

did_json.withWriter {
    writer ->
        ////将对象转成Json 方法1
        writer.write(JsonOutput.toJson(did_content))
}

gid_json.withWriter {
    writer ->
        ////将对象转成Json 方法1,但是使用 Category 功能
        writer.write(
                use(JsonOutput)
                    {
                        gid_content.toJson() //Category功能,将方法toJson 加到了 gid_content 中
                    }
        )
}


//解析Json文件
JsonSlurper jsonSlurper = new JsonSlurper()
def did_list = jsonSlurper.parse(did_json)

assert did_list instanceof List

(List)did_list.each {
    item ->
        assert item instanceof Map
        (Map)item.each {
            k,v ->
                println(k + ":" + v)
        }
}

//将对象转成Json 方法2
JsonBuilder jsonBuilder = new JsonBuilder()
jsonBuilder.content = did_list
println jsonBuilder.toPrettyString()

 

上一篇:Groovy有何不同 —— 类型篇


下一篇:持续集成高级篇之Jenkins参数传入与常见任务