Last active
August 15, 2016 23:45
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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