Java 8 - 使用 JsonObject (javax.json) - 如何确定一个节点是否有子节点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43045442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 8 - working with JsonObject (javax.json) - how to determine if a node has child nodes?
提问by Lurker
I've just started using javax.json package. I know how to extract values from JSON object in Java 8 if I know the structure of my JSON string. But how about strings I don't know the structure of? The question: how to determine if a node has child nodes?
我刚刚开始使用 javax.json 包。如果我知道 JSON 字符串的结构,我就知道如何从 Java 8 中的 JSON 对象中提取值。但是我不知道结构的字符串呢?问题:如何判断一个节点是否有子节点?
To read values, I simply need to use "get*" methods - it works OK, but there's no method like "checkIfArray" or "checkIfObject" to check if I even can use methods like "getString"...
要读取值,我只需要使用“get*”方法 - 它工作正常,但没有像“checkIfArray”或“checkIfObject”这样的方法来检查我是否甚至可以使用像“getString”这样的方法......
采纳答案by M. Prokhorov
In javax.json
package, both available types support emptiness checks because they both implement a java.collection
interfaces:
在javax.json
包中,两种可用类型都支持空检查,因为它们都实现了一个java.collection
接口:
JsonObject
is-a java.util.Map<String, JsonValue>
. As a result, one can check if such object contains any values by simply calling isEmpty()
method.
JsonObject
是-a java.util.Map<String, JsonValue>
。因此,可以通过简单地调用isEmpty()
方法来检查此类对象是否包含任何值。
JsonArray
is-a java.util.List<JsonValue>
. As a result, one - again - can check if the array is empty by calling isEmpty()
method on it.
JsonArray
是-a java.util.List<JsonValue>
。因此,再次 - 可以通过调用数组的isEmpty()
方法来检查数组是否为空。
For traversing a tree of JsonStructure
s while marking all empty nodes, you can use this helper method:
为了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
}
}