I have a JSON object which may contain a few null
values.
I use ObjectMapper
from com.fasterxml.jackson.databind
to convert my JSON object as String
.
private ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(object);
If my object contains any field that contains a value as null
, then that field is not included in the String
that comes from writeValueAsString()
.
I want my ObjectMapper
to give me all fields in the String
even if their value is null
.
Example:
object = {"name": "John", "id": 10}
json = {"name": "John", "id": 10}
object = {"name": "John", "id": null}
json = {"name": "John"}
To include null values in the JSON output of the FOR JSON clause, specify the INCLUDE_NULL_VALUES option. If you don't specify the INCLUDE_NULL_VALUES option, the JSON output doesn't include properties for values that are null in the query results.
With its default settings, Jackson serializes null-valued public fields. In other words, resulting JSON will include null fields. Here, the name field which is null is in the resulting JSON string.
Use writeValueAsString() method to get the JSON string representation of an object.
readValue() returns null for JSON input consisting of JSON value null . It does not return null for any other case: missing input (for example) would be rewarded by an exception; and no deserializer produces null by default.
Include.ALWAYS
worked for me.
objectMapper.setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include.ALWAYS);
Other possible values for Include
are:
Include.NON_DEFAULT
Include.NON_EMPTY
Include.NON_NULL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With