Skip to content

Instantly share code, notes, and snippets.

@paxan
Last active August 15, 2016 23:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paxan/72b0d7a32df4322cf0e1215342bd8e9a to your computer and use it in GitHub Desktop.
Save paxan/72b0d7a32df4322cf0e1215342bd8e9a to your computer and use it in GitHub Desktop.
Get the element in an arbitrarily nested JSON structure by following a path of keys (inspired by Clojure's get-in function)
package some.package;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import java.util.Arrays;
import java.util.Optional;
class SomeClass {
/**
* Returns the element in a nested JSON structure, where keys is a "path" of
* keys to traverse in order to retrieve the desired element.
* If the path is empty, returns the source structure as is.
* If the path leads to nowhere, returns empty {@link Optional<JsonElement>}.
*/
Optional<JsonElement> getIn(JsonElement e, String... keys) {
JsonElement v = Arrays.stream(keys).sequential()
.reduce(e,
(accumulator, key) -> {
if (accumulator.isJsonObject()) {
JsonElement nested = accumulator.getAsJsonObject().get(key);
return nested == null ? JsonNull.INSTANCE : nested;
} else {
return JsonNull.INSTANCE;
}
},
(x, y) -> x // combiner will never be called since this reduction is sequential (not parallel).
);
return v instanceof JsonNull ? Optional.empty() : Optional.of(v);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment