Enable the WriteValueAsString method of the Mapper to enable null values.

I have a JSON object that can contain multiple null values. I am using ObjectMapper from com.fasterxml.jackson.databind to convert my JSON object to String.

private ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(object); 

If my object contains any field containing a value as null, then this field is not on the line that comes from writeValueAsString. I want my ObjectMapper to give me all the fields in a 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"} 
+8
java json string jackson
source share
2 answers

Jackson must serialize fields null to null by default. See the following example.

 public class Example { public static void main(String... args) throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); String json = mapper.writeValueAsString(new Test()); System.out.println(json); } static class Test { private String help = "something"; private String nope = null; public String getHelp() { return help; } public void setHelp(String help) { this.help = help; } public String getNope() { return nope; } public void setNope(String nope) { this.nope = nope; } } } 

prints

 { "help" : "something", "nope" : null } 

You do not need to do anything special.

+5
source share

Include.ALWAYS worked for me.

 objectMapper.setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include.ALWAYS); 

Other possible values ​​for Include:

  • Include.NON_DEFAULT
  • Include.NON_EMPTY
  • Include.NON_NULL
0
source share

All Articles