【问题标题】:How to test for Empty array value in Unirest json Response如何在 Unirest json 响应中测试空数组值
【发布时间】:2021-06-04 09:23:43
【问题描述】:

我在 Jira Script Runner 云中使用了以下代码片段

String _userId
def result = get(graph_base_user_url + "?")
         .header("Authorization","Bearer " + AuthToken )
         .queryString("\$filter","mail eq '$userEmail'")
         .asJson()
        
        if (result.getStatus().toString() =="200")
        {
            **if (result.getBody().value){  // <<<<< is Value is not empty ???
              _userId=result.getBody().value[0].id    
            }** 
            else
            _userId="-1" // user does not exist
                                
        }
        // user ID not found : error 404
        if (result.getStatus().toString()=="404")
         _userId="User not found"

此代码在 result.getBody() 中返回以下输出

{"@odata.context":"https://graph.microsoft.com/v1.0/$metadata#users","value":[]}

我想要实现的是测试响应的值数组是否为空,如果不为空,我需要将第一个元素项获取为 value[0].Id,但我无法正确获取

我怎样才能在上面用粗体定义我的代码来执行我的正确测试? 我从代码中得到的错误是:“值不是 JsonNode 对象的属性

感谢您的帮助 问候

【问题讨论】:

    标签: groovy unirest jira-rest-java-api


    【解决方案1】:

    来自官方文档http://kong.github.io/unirest-java/#responses

    String result = Unirest.get("http://some.json.com")
                           .asJson()
                           .getBody()
                           .getObject()
                           .getJSONObject("car")
                           .getJSONArray("wheels")
                           .get(0)
    

    所以,这样的事情应该适合你:

    def a = result.getBody().getObject().getJSONArray("value")
    if(a.length()>0) _userId = a.get(0).get("id")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-26
      • 2018-01-22
      • 1970-01-01
      • 1970-01-01
      • 2013-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多