Get a JSON Value as Optional

This enables further filtering and mapping of a JSON Value.
pull/55/head
Richard Körber 2018-01-14 13:22:49 +01:00
parent 9a483fd4d1
commit 816f0825c0
No known key found for this signature in database
GPG Key ID: AAB9FD19C78AA3E0
2 changed files with 15 additions and 0 deletions

View File

@ -35,6 +35,7 @@ import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
@ -264,6 +265,16 @@ public final class JSON implements Serializable {
this.val = val;
}
/**
* Returns this value as {@link Optional}, for further mapping and filtering.
*
* @return {@link Optional} of this value, or {@link Optional#empty()} if this
* value is {@code null}.
*/
public Optional<Value> optional() {
return val != null ? Optional.of(this) : Optional.empty();
}
/**
* Checks if the value is present. An {@link AcmeProtocolException} is thrown if
* the value is {@code null}.

View File

@ -201,6 +201,8 @@ public class JSONTest {
assertThat(json.get("status").asStatusOrElse(Status.INVALID), is(Status.VALID));
assertThat(json.get("binary").asBinary(), is("Chainsaw".getBytes()));
assertThat(json.get("text").optional().isPresent(), is(true));
JSON.Array array = json.get("array").asArray();
assertThat(array.get(0).asString(), is("foo"));
assertThat(array.get(1).asInt(), is(987));
@ -241,6 +243,8 @@ public class JSONTest {
assertThat(json.get("none").orElse(42).asInt(), is(42));
assertThat(json.get("none").orElse(true).asBoolean(), is(true));
assertThat(json.get("none").optional().isPresent(), is(false));
try {
json.get("none").asInt();
fail("asInt did not fail");