我刚刚开始使用 javax.json 包。如果我知道我的 JSON 字符串的结构,我就知道如何从 Java 8 中的 JSON 对象中提取值。但是我不知道其结构的字符串呢?问题:如何判断一个节点是否有子节点?
要读取值,我只需要使用“get*”方法——它工作正常,但是没有像“checkIfArray”或“checkIfObject”这样的方法来检查我是否可以使用像“getString”这样的方法...
最佳答案
在javax.json
包,两种可用类型都支持空检查,因为它们都实现了 java.collection
接口(interface):
JsonObject
是一个java.util.Map<String, JsonValue>
.因此,可以通过简单地调用 isEmpty()
来检查此类对象是否包含任何值。方法。
JsonArray
是一个java.util.List<JsonValue>
.因此,可以再次通过调用 isEmpty()
检查数组是否为空。方法。
用于遍历 JsonStructure
的树s 在标记所有空节点时,您可以使用此辅助方法:
boolean isValueEmpty(JsonValue v) {
if (v == null) {
return true; // or you may throw an exception, for example
}
switch(v.getValueType()) {
case NULL:
return true; // same as with Java null, we assume that it is Empty
case ARRAY:
return ((JsonArray) v).isEmpty();
// additionally, you can say that empty array is array with only empty elements
// this means a check like this:
// return ((JsonArray v).stream().allMatch(isValueEmpty); // recurse
case OBJECT:
return ((JsonObject v).isEmpty();
case STRING:
// optionally: if you want to treat '' as empty
return ((JsonString v).getString().isEmpty();
default:
return false; // to my knowledge, no other Json types can be empty
}
}
关于Java 8 - 使用 JsonObject (javax.json) - 如何确定一个节点是否有子节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43045442/