我想从下面的httpResponse(JSON响应)中获取城市的价值,其中水果是苹果。我无法找到将这种条件添加到我的常规脚本中的方法。
{
"userInformation": {
"Name": "John",
"Location": "India"
},
"details": [
{
"fruit": "Apple",
"color": "Red",
"city": "New Delhi",
"luckyNumber": 10
},
{
"fruit": "Banana",
"color": "yellow",
"city": "Goa",
"luckyNumber": 12
}
]
}
答案 0 :(得分:2)
JsonSlurper
是您所需要的。它将JSON对象解析为普通的Map
,然后可以轻松地对其进行导航以找到所需的值。
import groovy.json.JsonSlurper
def input = '''{
"userInformation": {
"Name": "John",
"Location": "India"
},
"details": [
{
"fruit": "Apple",
"color": "Red",
"city": "New Delhi",
"luckyNumber": 10
},
{
"fruit": "Banana",
"color": "yellow",
"city": "Goa",
"luckyNumber": 12
}
]
}
'''
def slurped = new JsonSlurper().parseText(input)
slurped.details.find { it.fruit == 'Apple' }?.city