Ignore fields only in json but not xml with jackson-dataformat-xml

懵懂的女人 提交于 2019-12-01 11:12:29

问题


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>


来源:https://stackoverflow.com/questions/22903258/ignore-fields-only-in-json-but-not-xml-with-jackson-dataformat-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!