Json Slupper断言并提取

时间:2014-08-10 15:11:29

标签: json groovy extract soapui assert

我正在使用下一个Json

   {
  "ID": 8,
  "MenuItems": [
    {
      "ID": 38,
      "Name": "Home",
      "URL": "{\"PageLayout\":\"Home\",\"Icon\":\"home\"}",
      "Culture": "en",
      "Children": null
    },
    {
      "ID": 534,
      "Name": "GUIDE ",
      "URL": "{''PageLayout'':''Page A'', ''Icon'':''A''}",
      "MenuType": 1,
      "PageID": 0,
      "Culture": "en",
      "Children": [
        {
          "ID": 6,
          "Name": "Form A",
          "URL": "[''Type'':''Form A'',''Icon'':''Form'',''ItemID'':\"358\"]",
          "Culture": "he",
          "RuleID": 0
        },
        {
          "ID": 60,
          "Name": "Drama",
          "URL": "[''Type'':''Form B'',''Icon'':''Form'',''ItemID'':\"3759\"]",
          "Culture": "en",
          "RuleID": 0
        }
      ]
    }
  ]
}

我在soapUI中使用Groovy脚本,我需要:

  1. 断言具有名称GUIDE

  2. 的节点的退出
  3. 提取所有Itemsid的列表

1 个答案:

答案 0 :(得分:0)

您可以使用JsonSlurper解析JSON内容,然后像这样处理结果:

import groovy.json.JsonSlurper

// Assuming your JSON is stored in "jsonString"
def jsonContent = new JsonSlurper().parseText(jsonString)

// Assert node exists with name GUIDE
assert(jsonContent.MenuItems.Name.contains("GUIDE"))

// Get list of ItemIDs
def itemList = jsonContent.MenuItems.Children.URL.ItemID[0].toList()
// List the items
itemList.each {log.info it}

请注意,由于一些问题,鉴于您当前的示例,上述内容将失败。首先,名称包含" GUIDE" (尾随空间)而不是" GUIDE" (所以你需要相应调整)。其次,它是无效的JSON; URL节点有各种错误字符。

另外,如果您首先需要从现有testCase中与之前的TestStep(例如一个名为&#34; SendMessage&#34;)相关联的响应中检索您的JSON,则可以按如下方式进行:< / p>

def jsonString = context.testCase.getTestStepByName("SendMessage").testRequest.response.getContentAsString()