简体   繁体   中英

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?

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

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