嗨,我是groovy和API自动化的新手。我有以下Json,我想添加断言以根据序列号检查cyclestartdate和cycleEnddate。
{
"status" : "success",
"locale" : "",
"data" : {
"periods" : [
{
"payCycleId" : "custompayperiod",
"sequence" : 1,
"cycleStartDate" : "2018-10-01",
"cycleEndDate" : "2018-10-08"
},
{
"payCycleId" : "custompayperiod",
"sequence" : 2,
"cycleStartDate" : "2018-10-09",
"cycleEndDate" : "2018-10-16"
}
]
}
}
如何检查序列1 cycleStartDate是否为2018-10-01
答案 0 :(得分:2)
Groovy提供了JsonSlurper
类,使解析JSON文档更加容易。考虑以下示例,该示例将JSON文档读取为String
(它也支持其他初始化方法):
import groovy.json.JsonSlurper
def inputJson = '''{
"status" : "success",
"locale" : "",
"data" : {
"periods" : [
{
"payCycleId" : "custompayperiod",
"sequence" : 1,
"cycleStartDate" : "2018-10-01",
"cycleEndDate" : "2018-10-08"
},
{
"payCycleId" : "custompayperiod",
"sequence" : 2,
"cycleStartDate" : "2018-10-09",
"cycleEndDate" : "2018-10-16"
}
]
}
}'''
def json = new JsonSlurper().parseText(inputJson)
assert json.data.periods.find { it.sequence == 1 }.cycleStartDate == '2018-10-01'
已加载JSON文档,您可以通过访问嵌套字段来提取数据。例如,json.data.periods
使您可以访问存储在JSON文档中的数组。然后方法find { it.sequence == 1 }
从该数组返回一个节点,其中sequence
字段等于1
。最后,您可以提取cycleStartDate
并将其与预期日期进行比较。
您可以在Groovy's official documentation中找到更多有用的示例。