Created
October 11, 2017 18:33
-
-
Save BohdanLevchenko/066ca23ad8bdec69314e2925aef8aeda to your computer and use it in GitHub Desktop.
Json helper for nullable properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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