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

前端 未结 1 2006
北海茫月
北海茫月 2021-01-16 03:34

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 onl

相关标签:
1条回答
  • 2021-01-16 04:08

    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>
    
    0 讨论(0)
提交回复
热议问题