如何在 Unirest json 响应中测试空数组值

问题描述

我在 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 对象的属性

感谢帮助 问候

解决方法

来自官方文档 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")

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...