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

前端 未结 1 1874
[愿得一人]
[愿得一人] 2021-01-16 03:58

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条回答
  •  -上瘾入骨i
    2021-01-16 04:27

    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
    12
    

    0 讨论(0)
提交回复
热议问题