0

我在 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"
4

3 回答 3

0

正如我所见,天气是一系列地图。所以,你需要选择一个项目,否则 groovy 会返回给你一个 main 数组。

assert result.weather.first().main == "Clouds"
​assert result.weather.main == ["Clouds"​]​
于 2016-10-12T04:15:58.373 回答
0
于 2016-10-12T04:19:20.750 回答
0

weather in your json is array. You can access it elements as a regular array

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

second prefered because it null safe

于 2016-10-12T04:22:10.927 回答