Java 8 - working with JsonObject (javax.json) - how to determine if a node has child nodes?

I just started using javax.json package. I know how to extract values ​​from a JSON object in Java 8 if I know the structure of my JSON string. But what about strings, I don't know the structure? Question: how to determine if a node has child nodes?

To read the values, I just need to use the "get *" methods - it works fine, but there is no "checkIfArray" or "checkIfObject" method to check if I can even use methods like "getString" ...

+6
source share
1 answer

javax.json , java.collection:

JsonObject is-a java.util.Map<String, JsonValue>. , - , isEmpty().

JsonArray is-a java.util.List<JsonValue>. - - , , isEmpty().

JsonStructure :

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
  }
}
+6

Source: https://habr.com/ru/post/1016069/


All Articles