Groovy Calling/Looping 至 JSON 个对象

Groovy Calling/Looping through JSON Objects

我正在使用 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 calls/JSON 对象,并将所有响应项存储到它们自己的 variables/classes 中,并根据需要输出它们。

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

我要问你的问题是,我如何才能访问这些项目之一,并用 it/store 将它做成一个变量

下面是我的调试器输出

As getData() returns a 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