检查Gson JsonArray是否为空

Ale*_*ker 2 json gson

HttpURLConnection用来检索JSON字符串。看起来像这样:

{
  "status":"ok",
  "testSuites":[
    {
      // possibly one object in here
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我想知道数组是否为空。数组中最多有一个对象。我尝试了以下方法:

JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(json).getAsJsonObject();
JsonArray testSuites = obj.getAsJsonArray("testSuites");
Run Code Online (Sandbox Code Playgroud)

然后检查是否testSuitesnull,但这不起作用,因为不是null。但是它是空的!

Ale*_*ker 6

我想到了。您可以使用该size()方法确定数组中元素的数量。

if (testSuites.size() == 0)
Run Code Online (Sandbox Code Playgroud)