通过JSON对象进行Groovy调用/循环

时间:2016-08-10 18:15:41

标签: json groovy treemap

我正在使用groovy的RESTClient来制作HTTP GET请求并拥有一个JSON响应对象,看起来像这样

{   
    "page": 1,
    "pages": 1,
    "count": 4,
    "items": [{
        "id": 291938,
        "type": email,
        "folder": "1234",
        "isDraft": "false",
        "number": 349,
        "owner": {
            "id": 1234,
            "firstName": "Jack",
            "lastName": "Sprout",
            "email": "jack.sprout@gmail.com",
            "phone": null,
            "type": "user"
        },
        "mailbox": {
            "id": 1234,
            "name": "My Mailbox"
      }
    }]
}

我设置我的代码

def Client = new RESTClient('https://api.myapi.net/v1/conversations/' )
helpscout.setHeaders([Authorization: "Basic 1234", Accept: 'application/json'])
def resp = Client.get(contentType: JSON)
def myResponseObject = resp.getData()

我需要能够遍历多个API调用/ JSON对象,并将所有响应项存储到它们自己的变量/类中,并根据需要输出它们。

我来自python背景,习惯于通过说responseObject['items']['id']来调用特定项目,但在这种情况下,我无法做到。

我的问题是,我如何能够访问其中一个项目,并做任何我需要做的事情/将其存储到变量中

这是我的调试器输出 enter image description here

1 个答案:

答案 0 :(得分:2)

getData()返回Map时,你可以像这样引用JSON中的字段:

...
def myResponseObject = resp.getData()
def page = myResponseObject.page
def count = myResponseObject.count
println page // prints 1
println count //prints 4

// Print all items
myResponseObject.items.each {
    println "item: $it"
}

// The python example responseObject['items']['id'] in groovy is
responseObject.items[0].id

// To get the first items createdAt field (according to the image)
println responseObject.items[0].createdAt