在JSON HTTP响应中查找值

时间:2018-10-10 17:01:59

标签: java groovy httpresponse

我想从下面的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
         }
     ]
}

1 个答案:

答案 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