Enable Object Mapper writeValueAsString method to include null values

jackson, java, json, serialization, string

Solution

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.

Problem

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"} ```

Original source

Related problems