3

Using Jackson with the jackson-dataformat-xml module, I am able to serialize POJO to both JSON and XML. There are a few fields (xml attributes) in my object that should only be serialized to XML but not JSON. If I apply the @JsonIgnore annotation, the field is completely ignored even with @JsonXMLProperty.

How can I ignore fields only in JSON but not XML?

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
ltfishie
  • 2,917
  • 6
  • 41
  • 68

1 Answers1

3

You should use Mix-in feature. For example, assume that your POJO class looks like this:

class Pojo {

    private long id;
    private String xmlOnlyProperty;

    // getters, setters
}

Now, you can define annotations for each property using Mix-in interfaces. For JSON it looks like below:

interface PojoJsonMixIn {

    @JsonIgnore
    String getXmlOnlyProperty();
}

For XML it looks like below:

interface PojoXmlMixIn {

    @JacksonXmlProperty(isAttribute = true)
    String getXmlOnlyProperty();
}

Finally, example how to use Mix-in feature:

Pojo pojo = new Pojo();
pojo.setId(12);
pojo.setXmlOnlyProperty("XML attribute");

System.out.println("JSON");
ObjectMapper mapper = new ObjectMapper();
mapper.addMixInAnnotations(Pojo.class, PojoJsonMixIn.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(pojo));

System.out.println("XML");
ObjectMapper xmlMapper = new XmlMapper();
xmlMapper.addMixInAnnotations(Pojo.class, PojoXmlMixIn.class);
System.out.println(xmlMapper.writeValueAsString(pojo));

Above program prints:

JSON
{
  "id" : 12
}
XML
<Pojo xmlns="" xmlOnlyProperty="XML attribute"><id>12</id></Pojo>
Paul
  • 19,704
  • 14
  • 78
  • 96
Michał Ziober
  • 37,175
  • 18
  • 99
  • 146