访问groovy映射中的JSON元素

时间:2014-07-08 13:08:28

标签: json groovy httpbuilder

我试图访问某个json的元素从api调用返回到地图中,所以我可以将它传递给另一个api调用。我似乎不能正确地创造一个变量并给它我需要的价值。这是返回的json,我需要访问Id元素。

{
      "totalSize": 1,
      "done": true,
      "records":  [
         {
          "attributes":  {
            "type": "User",
            "url": "/services/data/v24.0/sobjects/User/MYIDNUMBER"
          },
          "Id": "MYIDNUMBER"
        }
      ]
    }

这里是我使用的休息服务电话以及我尝试访问Id元素并将其放入sfId以便我可以在我的下一个API调用中使用它

        def http = new HTTPBuilder(instance_domain)
        http.request(GET,JSON) { req ->
        uri.path = "services/data/v24.0/query/"
        uri.query = [q:"SELECT Id from User WHERE Email = '$loginid@myschool.edu'"]
        headers['Authorization'] = "Bearer $access_token"
            response.success = { resp, json  ->
            json.each{ key,value ->
             sfMap = [sfUser: [json: json]]
                }
            sfId = sfMap[records.Id]
            }
            response.failure = { resp, json ->
                    println resp.status
                    println json.errorCode
                    println json.message
                }                   
            }

我在部署了portletized版本的服务器上收到以下错误

2014-07-08 08:02:39,710 ERROR [http-bio-443-exec-161] portal-web.docroot.html.portal.render_portlet_jsp:154 groovy.lang.MissingPropertyException: No such property: records for class: groovyx.net.http.HTTPBuilder$RequestConfigDelegate

2 个答案:

答案 0 :(得分:1)

基于你的json结构,这就是我能说的。 records是一个数组,可能包含多个对象,因此Id s的数量。

def json = new groovy.json.JsonSlurper().parseText ("""
    {
          "totalSize": 1,
          "done": true,
          "records":  [
             {
              "attributes":  {
                "type": "User",
                "url": "/services/data/v24.0/sobjects/User/MYIDNUMBER"
              },
              "Id": "MYIDNUMBER"
            }
          ]
     }

""")

如果您确定第一个元素的ID,那么这将解决问题:

println json.records.first().Id

否则,这可能是更好的选项,它会为Id中的所有对象提供records

println json.records.collect{ it.Id }

答案 1 :(得分:0)

@kunal,这有帮助。

对于将来的参考,这里是我如何添加稍后要使用的变量的声明,从json response中为其赋值。

def http = new HTTPBuilder(instance_domain)
http.request(GET,JSON) { req ->
uri.path = "services/data/v24.0/query/"
uri.query = [q:"SELECT Id from User WHERE Email = '$loginid@myschool.edu'"]
headers['Authorization'] = "Bearer $access_token"
    response.success = { resp, json  ->
    sfId = json.records.first().Id    <----- this did the trick
    json.each{ key,value ->
     sfMap = [sfUser: [json: json]]
        }
    }
    response.failure = { resp, json ->
            println resp.status
            println json.errorCode
            println json.message
        }                   
    }