2014-07-08 94 views
0

我试图访问某个json从api调用返回到地图中的元素,因此我可以将它传递给另一个api调用。我似乎无法正确创建一个变量,并给它我需要的值。这里是返回的json,我需要访问Id元素。访问常规图中的JSON元素

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

这里的RESTful服务呼叫我使用,我试图访问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 = '[email protected]'"] 
     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 
+0

不应该是'json.records.Id'? – Will

+0

这就是我会想到的。试了很早就得到了'2014-07-08 08:24:54,735错误[http-bio-443-exec-170] portal-web.docroot.html.portal.render_portlet_jsp:154 java.lang.NullPointerException' – Baci

回答

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 S中所有对象的records

println json.records.collect{ it.Id } 
0

@kunal,这有帮助。

为了将来的参考,以下是我如何添加一个变量的定义以供稍后使用,从json响应中为其赋值。

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 = '[email protected]'"] 
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 
     }     
    }