12

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"}
Ihor Patsian
  • 1,270
  • 2
  • 15
  • 24
LINGS
  • 3,410
  • 5
  • 32
  • 45
  • It depends on the annotations on the type or how the mapper is configured, e.g., see [this](http://stackoverflow.com/questions/11757487/how-to-tell-jackson-to-ignore-a-field-during-serialization-if-its-value-is-null). – Giovanni Botta Apr 25 '14 at 17:14

2 Answers2

6

Jackson should serialize null fields 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 don't need to do anything special.

Sotirios Delimanolis
  • 263,859
  • 56
  • 671
  • 702
2

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
Ihor Patsian
  • 1,270
  • 2
  • 15
  • 24
Abbin Varghese
  • 1,892
  • 2
  • 23
  • 41