1

I have two java beans as below:

public class Class1 {
   private String field1;
   private Object field2;
   //getter and setter
}
public class Class2 {
  private Map<String,Object> field;
  //getter and setter
}

When the object gets serialized to Json, it looks like this:

Class1: When field2 is null

{
   field1:"value"
}

Class2: when value of map is null

{
   field:{"key":null}
}

My question is what is the difference between the two? why for Class1 it didn't include null field in json? How do I include null field in json for Class1? I have tried the following but did't work:

@JsonInclude(JsonInclude.Include.ALWAYS)
public class Class1 {
   private String field1;
   private Object field2;
   //getter and setter
}  

and even tried on field level:

public class Class1 {
   private String field1;
   @JsonInclude(JsonInclude.Include.ALWAYS)
   private Object field2;
   //getter and setter
}

I am using Jersey.

Amir Azizkhani
  • 1,662
  • 17
  • 30
Suraj h k
  • 163
  • 3
  • 17
  • Have your tried `@JsonInclude(Include.NON_NULL)`? – kazbeel Oct 25 '17 at 11:55
  • tried, but my requirement is to include null field. – Suraj h k Oct 25 '17 at 11:57
  • I think by default it won't include null fields, I tried @JsonInclude(JsonInclude.Include.ALWAYS) to include them in json but it didn't work. – Suraj h k Oct 25 '17 at 12:00
  • Yup, sorry my bad. What about customizing your own `ObjectMapper`? See [this answer](https://stackoverflow.com/a/25960533/815227) (where it actually makes the contrary of what you follow) – kazbeel Oct 25 '17 at 12:03
  • Possible duplicate of [How to tell Jackson to ignore a field during serialization if its value is null?](https://stackoverflow.com/questions/11757487/how-to-tell-jackson-to-ignore-a-field-during-serialization-if-its-value-is-null) – rkosegi Oct 25 '17 at 13:36
  • @rkosegi I want to include Null fields. How will it be duplicate question ? – Suraj h k Oct 25 '17 at 14:20
  • @Surajhk : if you read it, you should understand that it's actually "How to configure NULL field serialization" - so it is duplicate. – rkosegi Oct 25 '17 at 14:22
  • One more thing: make sure you are not accidentally using Jackson 1.x annotations (from `org.codehaus.jackson.annotation`). Jackson 2.x annotations are in different package (`com.fasterxml.jackson.annotation`), but since names are same it is possible to sometimes get the two confused if both versions are in classpath (IDE shows both for auto-completion). – StaxMan Oct 25 '17 at 22:30

1 Answers1

2

The following example is with jackson:

ObjectMapper mapper = new ObjectMapper();
Class1 class1 = new Main().new Class1();
System.out.println(mapper.writeValueAsString(class1));

and the output is:

{"field1":null,"field2":null}

ddarellis
  • 3,912
  • 3
  • 25
  • 53