2016-10-12 6 views
0

JSON 응답에 어설 션을 실행하려면 SOAPUI에 다음과 같은 그루비 스크립트를 작성했습니다.Groovy에서 JsonSlurper를 사용하여 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" 

답변

0

날씨는 내가 보는 것처럼지도의 배열입니다. 따라서 항목을 선택해야하거나 그루비가 주 배열을 반환합니다.

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

사소한 문제입니다.

weather은 ([] 안에있는) 배열이며 어설 션이 실패하는 이유입니다. 당신이 result.weather​.main​을 할 경우

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

는, 다음은 요소 Clouds를 포함하는 목록을 반환합니다. 하지만, 당신이 기대했던 것과 같은 단일 가치는 아닙니다.

그래서, 당신은 할 수 있습니다 :

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

: 날씨 (JSON 배열에 더 많은 요소와 예) 아래

assert result.weather​[0].main == 'Clouds', 'Not matching the expected result' 또는
assert result.weather​.main == ['Clouds'] 또는 가정 해 들어 assert result.weather.main.contains('Clouds')


경우 그런 다음 단언 할 수 있습니다 assert result.weather.main == ['Clouds', 'CloudApps']

0

json의 날씨는 배열입니다. 당신은 규칙적인 배열로에게

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

초 선호를 요소에 액세스 할 수 있습니다 그것은 널 안전

때문에
관련 문제