简体   繁体   中英

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.

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM