Suraj h k
Suraj h k

Reputation: 173

Jackson java object to json serialization is not including null fields

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.

Upvotes: 1

Views: 1631

Answers (1)

ddarellis
ddarellis

Reputation: 3960

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}

Upvotes: 2

Related Questions