JAXB annotations for nested element lists

前端 未结 1 1541
感动是毒
感动是毒 2020-12-03 08:11

I have the following XML:


    
        asdas
        

        
相关标签:
1条回答
  • 2020-12-03 08:54

    By default JAXB (JSR-222) implementations consider public properties (get/set methods) and annotated fields as mapped (and separate). The default mapping is @XmlElement so your properties will be considered as mapped this way.

    Solution #1

    Since you are annotating the fields you need to add @XmlAccessorType(XmlAccessType.FIELD) on your classes.

    @XmlAccessorType(XmlAccessType.FIELD)
    public class Parameter {
        @XmlAttribute(name = "attr")
        private String mName;
    
        @XmlValue
        private String mValue;
    
        public String getName() {
            return mName;
        }
    
        public void setName(String aName) {
            this.mName = aName;
        }
    
        public String getValue() {
            return mValue;
        }
    
        public void setValue(String aValue) {
            this.mValue = aValue;
        }
    }
    

    Solution #2

    Annotate the get (or set) methods.

    public class Parameter {
        private String mName;
    
         private String mValue;
    
        @XmlAttribute(name = "attr")
        public String getName() {
            return mName;
        }
    
        public void setName(String aName) {
            this.mName = aName;
        }
    
        @XmlValue
        public String getValue() {
            return mValue;
        }
    
        public void setValue(String aValue) {
            this.mValue = aValue;
        }
    }
    

    For More Information

    • http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html
    • http://blog.bdoughan.com/2011/06/jaxb-and-complex-types-with-simple.html

    UPDATE

    You will also need to use the @XmlElement annotation on the mappings property to specify the element name should be mapping.

    @XmlRootElement(name = "mappings")
    public class Mappings { 
        private List<Mapping> mMappings;
    
        @XmlElement(name="mapping")
        public List<Mapping> getMappings() {
            return mMappings;
        }
    
        public void setMappings(List<Mapping> aMappings) {
            this.mMappings = aMappings;
        }
    }
    
    0 讨论(0)
提交回复
热议问题