Mubin
Mubin

Reputation: 4239

Override @JsonInclude(Include.NON_NULL) from POJO in ObjectMapper

Question: Is it possible to override Include.NON_NULL defined in the POJO while creating the ObjectMapper?

Explanation:

Suppose I have a POJO as below:

@JsonInclude(Include.NON_NULL)
class POJO {
  String name;
  String description;
  //Constructors, Getters & Setters, etc
}

And a test class as below:

class Main {
  public static void main(String args[]) {
    POJO p = new POJO();
    ObjectMapper mapper = new ObjectMapper();
     String jsonString = mapper.setSerializationInclusion(Include.ALWAYS)
                               .writerWithDefaultPrettyPrinter()
                               .writeValueAsString(p);
    //jsonString should contain empty name & description fields, but they doesn't
  }
}

Upvotes: 5

Views: 3332

Answers (1)

Franjavi
Franjavi

Reputation: 657

You can use a mix-in, since it has priority over annotations.

@JsonInclude(JsonInclude.Include.ALWAYS)
public class MixIn {
}

And add it to the mapper

ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(POJO.class, MixIn.class);

The result will be

{"name":null,"description":null}

Upvotes: 5

Related Questions