[英]Access to JSON element in groovy map
我正在尝试访问通过api调用返回到地图的json元素,因此我可以将其传递给另一个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
根据您的json结构,这就是我可以说的。 records
是一个数组,可能包含多个对象,因此可能包含Id
。
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
否则,这可能是一个更好的选择,它将为您提供records
中所有对象的Id
。
println json.records.collect{ it.Id }
@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 = '$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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.