如何使用ScriptRunner Groovy脚本获取Array项

时间:2020-07-03 15:36:39

标签: groovy jira

我正在Jira的脚本运行程序中使用MSGraph API和groovy脚本,以便通过其电子邮件地址检索一个guets AD用户。

我用于执行此操作的代码如下:

public String getGuestUserId(String AuthToken,String userEmail){

    String _userId
    def http = new HTTPBuilder(graph_base_user_url + "?")

        http.request(GET) {

            requestContentType = ContentType.JSON
            //uri.query = [ $filter:"mail eq '$userEmail'"].toString()
            uri.query=[$filter:"mail eq '$userEmail'"]

            headers.'Authorization' = "Bearer " + AuthToken    

            response.success = { resp, json ->
                _userId=json["value"]
            }

            // user ID not found : error 404
            response.'404' = { resp ->       
                _userId = 'Not Found'
            }

        }
        _userId
    } 

此调用的输出如下:

[{businessPhones=[], displayName=user test, givenName=null, jobTitle=null, 
mail=user1@gmail.com, mobilePhone=null, officeLocation=null, preferredLanguage=null, 
surname=null, userPrincipalName=user1_gmail.com#EXT#@rlxcom.onmicrosoft.com, id=7982c558- 
ba50-4380-9e94-114d8b340720}]

IT代表Array对象的单个用户输出。

仅检索此返回数组的 Id 部分的方法是什么?

我已经尝试使用:p从我的方法直接返回

response.success = { resp, json ->
_userId=json["value"][0]["Id"]

但是它不起作用

==>更新

如果我只是使用下面的代码部分来查看解析Json是否可以,我会收到异常错误:

def json = new groovy.json.JsonSlurper().parseText ret
return json

groovy.json.JsonException:期望为'}'或',',但当前字符为'b',其int值为98

当前读取的字符为'b',int值为98 预期为'}'或',但得到的当前char'b'的int值为98 行号1 索引号2

====更新2 ===

如果我将方法json repsonse更改为:

response.success = { resp, json ->
            _userId=json["value"].toString()
        }

返回值为json:

String json=apiHelper.getGuestUserId(apiHelper.Token,email)

返回如下(注意,没有{})

[[businessPhones:[], displayName:serge cal test, givenName:null, 
jobTitle:null, mail:calderara.serge@gmail.com, mobilePhone:null, 
officeLocation:null, preferredLanguage:null, surname:null, 
userPrincipalName:calderara.serge_gmail.com#EXT#@rlxcom.onmicrosoft.com, 
id:7982c558-ba50-4380-9e94-114d8b340720]]

调用该函数,然后根据您的示例解析以下方法:

def retVal = new groovy.json.JsonSlurper().parseText (json) 
return retVal.id.first()

然后,它失败了,与我最初的帖子一样,因为它不是Json格式的返回值,而是数组项。

有什么想法如何根据上面的返回字符串使它工作吗?

1 个答案:

答案 0 :(得分:0)

如果您需要获取所有ID(通用解决方案):

String str = """{"value":[{"businessPhones":"[]", "displayName":"user test", "givenName":null, "jobTitle":null,
"mail":"user1@gmail.com", "mobilePhone":null, "officeLocation":null, "preferredLanguage":null, "surname":null,
"userPrincipalName":"user1_gmail.com#EXT#@rlxcom.onmicrosoft.com", "id":"7982c558-ba50-4380-9e94-114d8b340720"}]}"""

def json = new groovy.json.JsonSlurper().parseText str

def ids = json.value*.id
assert ['7982c558-ba50-4380-9e94-114d8b340720'] == ids

您的具体案例:

http.request(GET) {

  //...

  response.success = { resp, json ->
    _userId = json.value[ 0 ].id
    // or
    _userId=json.value*.id.first()
  }
}