忽略json中的字段,但不使用jackson-dataformat-xml忽略xml [英] Ignore fields only in json but not xml with jackson-dataformat-xml

查看:1938
本文介绍了忽略json中的字段,但不使用jackson-dataformat-xml忽略xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将jackson与jackson-dataformat-xml模块一起使用,我可以将POJO序列化为json和xml。我的对象中有一些字段(xml属性)只应序列化为XML而不是json。如果我应用@JsonIgnore注释,即使使用@JsonXMLProperty也会完全忽略该字段。

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.

如何只忽略json中的字段而不忽略xml?

How can I ignore fields only in json but not xml?

推荐答案

你应该使用混合功能。例如,假设您的 POJO 类如下所示:

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
}

现在,你可以使用混合接口为每个属性定义注释。对于 JSON ,它如下所示:

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

interface PojoJsonMixIn {

    @JsonIgnore
    String getXmlOnlyProperty();
}

对于 XML 它如下所示:

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>

这篇关于忽略json中的字段,但不使用jackson-dataformat-xml忽略xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆