mirror of https://github.com/shred/acme4j
Get a JSON Value as Optional
This enables further filtering and mapping of a JSON Value.pull/55/head
parent
9a483fd4d1
commit
816f0825c0
|
@ -35,6 +35,7 @@ import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.NoSuchElementException;
|
import java.util.NoSuchElementException;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
import java.util.Optional;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
import java.util.stream.StreamSupport;
|
import java.util.stream.StreamSupport;
|
||||||
|
@ -264,6 +265,16 @@ public final class JSON implements Serializable {
|
||||||
this.val = val;
|
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
|
* Checks if the value is present. An {@link AcmeProtocolException} is thrown if
|
||||||
* the value is {@code null}.
|
* the value is {@code null}.
|
||||||
|
|
|
@ -201,6 +201,8 @@ public class JSONTest {
|
||||||
assertThat(json.get("status").asStatusOrElse(Status.INVALID), is(Status.VALID));
|
assertThat(json.get("status").asStatusOrElse(Status.INVALID), is(Status.VALID));
|
||||||
assertThat(json.get("binary").asBinary(), is("Chainsaw".getBytes()));
|
assertThat(json.get("binary").asBinary(), is("Chainsaw".getBytes()));
|
||||||
|
|
||||||
|
assertThat(json.get("text").optional().isPresent(), is(true));
|
||||||
|
|
||||||
JSON.Array array = json.get("array").asArray();
|
JSON.Array array = json.get("array").asArray();
|
||||||
assertThat(array.get(0).asString(), is("foo"));
|
assertThat(array.get(0).asString(), is("foo"));
|
||||||
assertThat(array.get(1).asInt(), is(987));
|
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(42).asInt(), is(42));
|
||||||
assertThat(json.get("none").orElse(true).asBoolean(), is(true));
|
assertThat(json.get("none").orElse(true).asBoolean(), is(true));
|
||||||
|
|
||||||
|
assertThat(json.get("none").optional().isPresent(), is(false));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
json.get("none").asInt();
|
json.get("none").asInt();
|
||||||
fail("asInt did not fail");
|
fail("asInt did not fail");
|
||||||
|
|
Loading…
Reference in New Issue