如何在 Groovy 中使用 JsonSlurper 提取 JSON 参数

How to extract JSON parameter using JsonSlurper in Groovy

我在 SOAPUI 中编写了以下 groovy 脚本来对 JSON 响应执行断言。

我在编写断言以提取和断言 Weather > main > Clouds 属性 和 JSON 响应的值时遇到困难。

有人可以协助更正我的代码以提取我想要的值吗?

谢谢!

import groovy.json.JsonSlurper

def json = '''{
"coord": {
  "lon": -0.13,
  "lat": 51.51
  },
 "weather": [
  {
     "id": 801,
     "main": "Clouds",
     "description": "few clouds",
     "icon": "02n"
  }
  ],
 "base": "stations",
  "main": {
  "temp": 281.644,
  "pressure": 1027.43,
  "humidity": 100,
  "temp_min": 281.644,
  "temp_max": 281.644,
  "sea_level": 1035.14,
  "grnd_level": 1027.43
   },
  "wind": {
  "speed": 3.33,
  "deg": 43.5005
 },
 "clouds": {
  "all": 12
 },
 "dt": 1476231232,
  "sys": {
  "message": 0.0084,
  "country": "GB",
  "sunrise": 1476253200,
  "sunset": 1476292372
},
  "id": 2643743,
 "name": "London",
 "cod": 200
   }'''


def result = new JsonSlurper().parseText(json)
log.info(result)
assert result.weather.main == "Clouds"

正如我所见,天气是一组地图。所以,你需要 select 一个项目或者 groovy 将 return 给你一个主要的数组。

assert result.weather.first().main == "Clouds"
​assert result.weather.main == ["Clouds"​]​

看起来这是一个微不足道的问题。

weather 是一个数组(在 [] 中),这就是断言失败的原因。

"weather": [
  {
     "id": 801,
     "main": "Clouds",
     "description": "few clouds",
     "icon": "02n"
  }
  ],

如果您执行 result.weather​.main​,那么它将 returns 一个包含元素 Clouds 的列表。但是,没有您预期的单个值。

所以,你可以这样做:

assert result.weather​[0].main == 'Clouds', 'Not matching the expected result'
assert result.weather​.main == ['Clouds']
assert result.weather.main.contains('Clouds')

假设天气低于(json 数组中有更多元素的示例):

"weather": [
  {
     "id": 801,
     "main": "Clouds",
     "description": "few clouds",
     "icon": "02n"
  },
  {
     "id": 802,
     "main": "CloudApps",
     "description": "few clouds",
     "icon": "03n"
  }
  ],

然后就可以断言了 assert result.weather.main == ['Clouds', 'CloudApps']

您 json 中的天气是数组。您可以将其元素作为常规数组访问

assert result.weather.main[0] == "Clouds"
assert result?.weather?.main?.getAt(0) == "Clouds"

第二首选,因为它空安全