JAXB Avoid saving default values

后端 未结 2 851
余生分开走
余生分开走 2021-01-13 05:01

Is there any way to make JAXB not save fields which values are the default values specified in the @Element annotations, and then make set the value to it when loading eleme

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-13 05:42

    You could do something like the following by leveraging XmlAccessorType(XmlAccessType.FIELD) and putting logic in the get/set methods:

    Example

    package forum8885011;
    
    import javax.xml.bind.annotation.*;
    
    @XmlRootElement
    @XmlAccessorType(XmlAccessType.FIELD)
    class Example {
    
        private static final String PROP1_DEFAULT = "default1";
        private static final String PROP2_DEFAULT = "123";
    
        @XmlElement(defaultValue=PROP1_DEFAULT)
        String prop1;
    
        @XmlElement(defaultValue=PROP2_DEFAULT)
        Integer prop2;
    
        public String getProp1() {
            if(null == prop1) {
                return PROP1_DEFAULT;
            }
            return prop1;
        }
    
        public void setProp1(String value) {
            if(PROP1_DEFAULT.equals(value)) {
                prop1 = null;
            } else {
                prop1 = value;
            }
        }
    
        public int getProp2() {
            if(null == prop2) {
                return Integer.valueOf(PROP2_DEFAULT);
            }
            return prop2;
        }
    
        public void setProp2(int value) {
            if(PROP2_DEFAULT.equals(String.valueOf(value))) {
                prop2 = null;
            } else {
                prop2 = value;
            }
        }
    
    }
    

    Demo

    package forum8885011;
    
    import javax.xml.bind.*;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            JAXBContext jc = JAXBContext.newInstance(Example.class);
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    
            Example example = new Example();
            example.setProp1("default1");
            example.setProp2(123);
            System.out.println(example.getProp1());
            System.out.println(example.getProp2());
            marshaller.marshal(example, System.out);
    
            example.setProp1("FOO");
            example.setProp2(456);
            System.out.println(example.getProp1());
            System.out.println(example.getProp2());
            marshaller.marshal(example, System.out);
        }
    
    }
    

    Output

    default1
    123
    
    
    FOO
    456
    
    
        FOO
        456
    
    

    For More Information

    • http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html

提交回复
热议问题