groovy - 如何使用groovy脚本从Json获取值

标签 groovy

您好,我是 groovy 和 API 自动化的新手。我有以下 Json,我想添加断言来根据序列号检查周期开始日期和周期结束日期。

{
   "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

最佳答案

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并将其与预期日期进行比较。

You can find more useful examples in Groovy's official documentation.

关于groovy - 如何使用groovy脚本从Json获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52824137/

相关文章:

groovy - 导入其他常规脚本-出现错误

java - 如何在 jar 中包含 Groovy 扩展方法?

database - ArrayIndexOutOfBoundsException失败

testing - gradle 测试阶段?

hibernate - 使用不可变嵌入对象的 Grails GORM

grails - Groovy 方法重载

mysql - 在groovy中调用mysql存储过程

grails - 有人可以建议学习grails 3上快速刻线的最佳方法吗?

android - 如果 Android Gradle Build 中不存在默认属性文件,我该如何创建它

google-app-engine - Gaelyk:如何对集合属性执行数据存储查询