4 ms·
If you're asking for a example you'd be more likely to use, JSON is a pretty good example. The GSON interface [0] has isArray()/getAsJsonArray(), isObject()/get
by rovolo 6y ago
If you're asking for a example you'd be more likely to use, JSON is a pretty good example. The GSON interface [0] has isArray()/getAsJsonArray(), isObject()/getAsJsonObject(), etc. for determining the type of an element, but this isn't type-safe. Pattern matching is a more convenient way to work with raw JSON:
public int countNodes(JsonElement el) {
return switch(el) {
case JsonObject obj ->
obj.entrySet().stream()
.mapToInt(e -> countNodes(e.getValue())).sum()
case JsonArray arr ->
arr.stream().mapToInt(::countNodes).sum()
default -> 1
}
}
[0] https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/JsonElement.html https://www.javadoc.io/doc/com.google.code.gson/gson/latest/...