javajacksonjackson-databindjackson-dataformat-xml

@JsonInclude filtering by class' attribute


I am working on serializing classes to XML. I've found @JsonInclude to be immensely helpful. However, I am having issues on filtering a class by its attribute. In the xml, if it's a US address I need to have one set of annotations for the fields using @JsonProperty. Because of this, I'm trying to use the Include annotation to only show the relevant field based on the country.

The US address needs to have USAddress as the wrapper element name. Foreign Addresses need to have ForeignAddress as the wrapper element name as well as different element names for state/zip.

Is there a way to access the class and it's attributes in the filter? I've tried using the super class for both types of addresses, but with Bazel, I run into circular dependency issues when doing that. Im super new to bazel :P

public class Thing {
  @JsonInclude(value = Include.CUSTOM, valueFilter = CountryFilter.class)
  private final USAddress usAddress = new USAddress({line1: "123 MockingBird Ln", country: "US"});
  @JsonInclude(value = Include.CUSTOM, valueFilter = CountryFilter.class)
  private final ForeignAddress foreignAddress = new ForeignAddress({line1: "123 MockingBird Ln", country: "DE"});
}

public class CountryFilter {
  @Override
  public boolean equals(Object obj) {
    return ...; // This is where I'm having issues. Would like it to do something like obj.getCountry().equals("US").
  }
}

Solution

  • I ended up using the @JsonInclude(Include.NON_NULL) and then used a conditional in the constructor to optionally set the address.