Few tips in practice
Let's have a look at the following tips:
- Dealing with null: If you use the following code and try to obtain the JSON string, then you might be surprised by the output:
Issue issue= new Issue(); issue.setId(200L); issue.setName("Test"); issue.setPriority(null); Jsonb jsonb = JsonbBuilder.create(); String jsonString = jsonb.toJson(issue); // JSON String
Here, the output would ignore the priority
field as it's having a null value. This is the default behavior, but it can be changed using multiple ways. A convenient option is to change it globally by using the JsonbConfig
class:
JsonbConfig nillableConfig = new JsonbConfig() .withNullValues(true);
Other options include using the @JsonbNillable
annotation on the class or using @JsonbProperty(nillable=true)
.
- Use Adapters for more control: When annotations aren't an option, such as for cases where you may not be in control of the code of the class which is being serialized, then you can make...