Skip to content

Instantly share code, notes, and snippets.

@BohdanLevchenko
Created October 11, 2017 18:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BohdanLevchenko/066ca23ad8bdec69314e2925aef8aeda to your computer and use it in GitHub Desktop.
Save BohdanLevchenko/066ca23ad8bdec69314e2925aef8aeda to your computer and use it in GitHub Desktop.
Json helper for nullable properties
import javax.json.*;
/**
* Usage:
* class SomeClass {
* //...
* public JsonValue toJson() {
* return Json.createObjectBuilder().add("id", this.someId)
* .add("zipCode", SafeJson.nvl(this.someNullableInt))
* .add("phone", SafeJson.nvl(this.someNullableString))
* .add("date", SafeJson.nvl(this.someNullableDate))
* .build();
* }
* //...
* }
* Note: This strange construction `Json.createObjectBuilder().add(KEY, ref).build().get(KEY);`
* is needed to get value wrapped in `JsonValue` (the only portable way I've found so far).
* In JavaEE 8 however it is possible using `Json.createValue()` or underlying
* `JsonProvider.provider().createValue()` methods.
*/
public final class SafeJson {
private static final String KEY = "1";
public static JsonValue nvl(final String ref) {
if (ref == null) {
return JsonValue.NULL;
}
return Json.createObjectBuilder().add(KEY, ref).build().get(KEY);
}
public static JsonValue nvl(final Integer ref) {
if (ref == null) {
return JsonValue.NULL;
}
return Json.createObjectBuilder().add(KEY, ref).build().get(KEY);
}
public static JsonValue nvl(final java.sql.Date ref) {
if (ref == null) {
return JsonValue.NULL;
}
return Json.createObjectBuilder().add(KEY, ref.getTime()).build().get(KEY);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment