13

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,288
  • 2
  • 15
  • 25
LINGS
  • 3,560
  • 5
  • 34
  • 47
  • 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

3 Answers3

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
  • 274,122
  • 60
  • 696
  • 724
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,288
  • 2
  • 15
  • 25
Abbin Varghese
  • 2,422
  • 5
  • 28
  • 42
1

I've faced similar issue with SpringBoot, it could miss the getter function for the entity class.

I included @Getter in spring entity class and it was fixed.

Ananda G
  • 2,389
  • 23
  • 39