【问题标题】:Groovy Calling/Looping through JSON Objects通过 JSON 对象进行 Groovy 调用/循环
【发布时间】:2016-08-10 18:15:40
【问题描述】:

我正在使用 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'] 来调用特定项目,但在这种情况下我不能这样做。

我的问题是,我怎样才能访问这些项目之一,并做我需要做的任何事情/将其存储到变量中

这是我下面的调试器输出

【问题讨论】:

  • 您确定您提供的示例 json 与端点返回的相同吗?
  • 呸!更新了调试器中的实际 JSON 输出 现在打印出整数
  • 如果您将从端点获得的实际 JSON 作为文本提供而不是提供调试器的屏幕截图,那么提供一些帮助会容易得多。根据截图,JSON 完全不同

标签: json groovy treemap


【解决方案1】:

由于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

【讨论】:

  • 我试过了,页面返回null,看我添加到问题中的截图
  • 根据图像myResponseObject 有一个名为item 的条目,试试这样:myResponseObject.item.page
  • 将item store 放入一个变量中,那么调用特定item 或field 怎么办?
  • 我不知道你是什么意思调用一个特定的项目,你能举个例子你想对这些字段做什么吗?
  • 我该如何引用 myResponseObject.items[1][4] ?它的输出应该是 2016-08-10T19:17:30Z
猜你喜欢
  • 2021-05-05
  • 2016-10-11
  • 1970-01-01
  • 2021-10-30
  • 2020-04-28
  • 2017-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多