Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable Object Mapper writeValueAsString method to include null values

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"}
like image 494
LINGS Avatar asked Apr 25 '14 15:04

LINGS


People also ask

How do I allow null values in JSON?

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.

Does Jackson serialize null fields?

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.

What is the use of writeValueAsString in Java?

Use writeValueAsString() method to get the JSON string representation of an object.

Can ObjectMapper readValue return null?

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.


1 Answers

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
like image 123
Abbin Varghese Avatar answered Sep 20 '22 11:09

Abbin Varghese