Search code examples
javajsonjacksonfasterxmljackson-databind

How to serialize values which are provided JsonInclude.Include.NON_NULL at class level


Currently my application has a class which is as below

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Employee {
  Department department;
  String firstName;
  String lastName;
  String address;
  String phoneNumber;
}

I am capturing the employee object inside the logs where I am converting the object into JSON. I am able to convert the object to JSON but the null values do not get into the JSON.

I have tried the below

 objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
 generator.setCodec(objectMapper);
 generator.writeObjectField(fieldName, argument);

But not able to get the null values of the fields in JSON. How do I get them?


Solution

  • You can copy an ObjectMapper and change some of its options, in this case you can ignore annotations:

    ObjectMapper mapperIgnoringAnnotations = mapper.copy()
            .disable(MapperFeature.USE_ANNOTATIONS)
            .setSerializationInclusion(JsonInclude.Include.ALWAYS)
            .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
    

    Then use this modified ObjectMapper to serialize this class but the standard one for the other classes. Not convenient if Employee has many other annotations that you want to take into account.

    USE_ANNOTATIONS