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

时间:2016-10-12 03:12:34

标签: json groovy soapui jsonslurper

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

我在编写断言以提取和断言天气>时遇到困难。主要> 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"

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

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

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

如果您执行result.weather​.main​,则会返回包含元素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']

答案 2 :(得分:0)

json中的天气是阵列。您可以将它作为常规数组

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

第二个首选因为它安全无效