简体   繁体   English

如何在 Gson JsonObject 中检查“isEmpty()”?

[英]How to check "isEmpty()" in Gson JsonObject?

I used the Google Gson API to construct JSON.我使用 Google Gson API 来构建 JSON。 When I initialized a JsonObject with:当我使用以下命令初始化 JsonObject 时:

JsonObject json = new JsonObject();

and print it out, it was in fact {} .并打印出来,它实际上是{}

I tried to exclude the "empty" JSON, ie the {} ones that were not added any properties.我试图排除“空”JSON,即未添加任何属性的{} But I could not find a method resembling isEmpty() in the Gson API.但是我在 Gson API 中找不到类似于isEmpty()的方法。

How can I find out the "empty" JSON with Gson API?如何使用 Gson API 找出“空”JSON?

You can use JsonObject#entrySet() to get the JSON object's set of name/value pairs (its members).您可以使用JsonObject#entrySet()来获取 JSON 对象的一组名称/值对(其成员)。 That returns a Set which has the traditional isEmpty() method you're looking for.这将返回一个Set ,其中包含您正在寻找的传统isEmpty()方法。

For example,例如,

JsonObject jsonObject = ...;
Set<Map.Entry<String,JsonElement>> members = jsonObject.entrySet();
if (members.isEmpty()) {
    // do something
}

Its more correct to use the Set.isEmpty() for this purpose为此目的使用Set.isEmpty()更正确

if (jsonObject.entrySet().isEmpty()) {

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM