Reputation: 31
Recently, I started using Optional when handling json response in our project:
Optional.ofNullable(root.get("a"))
.map(a -> a.get("b"))
.map(b -> b.get("c"))
.map(c -> c.get("d"))
for each get(), I have to use a map() to keep the return value in the "safety box" which makes the code quite verbose. To access a very deep json field in a complex long json tree, it would end up with a quite long map() chain.
I was dreaming of something like this:
Optional.ofNullable(root.get("a")).map(a.get("b").get("c").get("d"))
If any of those get() methods returns a null value, I would get an empty Optional as result of the expression. Let's say, using one "safety box", all possible null values can be somehow handled and turned into empty Optional. Is it a silly thought?
Is there a way to make the code less-verbose?
Upvotes: 2
Views: 667
Reputation: 140504
Wrap it up inside a method:
static Optional<JsonObject> get(JsonObject root, String... paths) {
Optional<JsonObject> opt = Optional.ofNullable(root);
for (String p : paths) {
if (!opt.isPresent()) break;
opt = opt.map(a -> a.get(p));
}
return opt;
}
then call like:
Optional<JsonObject> jsonObject = get(root, "a", "b", "c", "d");
Upvotes: 3