Set default value for optional JSON keys

pull/55/head
Richard Körber 2017-12-13 23:24:03 +01:00
parent 2ceffa42e3
commit 173aa14e40
No known key found for this signature in database
GPG Key ID: AAB9FD19C78AA3E0
2 changed files with 14 additions and 0 deletions

View File

@ -277,6 +277,16 @@ public final class JSON implements Serializable {
return this; return this;
} }
/**
* Checks if the value is present. If not, the default value is used instead.
*
* @param def Default value
* @return itself
*/
public Value orElse(Object def) {
return val != null ? this : new Value(path, def);
}
/** /**
* Returns the value as {@link String}. * Returns the value as {@link String}.
* *

View File

@ -237,6 +237,10 @@ public class JSONTest {
assertThat(json.get("none").asBinary(), is(nullValue())); assertThat(json.get("none").asBinary(), is(nullValue()));
assertThat(json.get("none").asProblem(BASE_URL), is(nullValue())); assertThat(json.get("none").asProblem(BASE_URL), is(nullValue()));
assertThat(json.get("none").orElse("foo").asString(), is("foo"));
assertThat(json.get("none").orElse(42).asInt(), is(42));
assertThat(json.get("none").orElse(true).asBoolean(), is(true));
try { try {
json.get("none").asInt(); json.get("none").asInt();
fail("asInt did not fail"); fail("asInt did not fail");