Ignore fields only in json but not xml with jackso

2020-03-31 02:16发布

问题:

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 and 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?

回答1:

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>