Binding a Generic Java Class to a JSON using JAXB

后端 未结 1 1884
野趣味
野趣味 2021-02-10 04:02

I have the following java class

@XmlRootElement
@XmlSeeAlso(DataClass.class)
public static class EnvelopeClass {

    @XmlElement
    public String vers         


        
相关标签:
1条回答
  • 2021-02-10 04:22

    To get the desired behaviour, you can use @XmlAnyElement on the data property instead of @XmlElement. For the @XmlAnyElement property the value will correspond to a class with the matching @XmlRootElement annotation.

    EnvelopeClass

    import javax.xml.bind.annotation.XmlAnyElement;
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlRootElement;
    import javax.xml.bind.annotation.XmlSeeAlso;
    
    @XmlRootElement 
    @XmlSeeAlso(DataClass.class) 
    public class EnvelopeClass<T> { 
    
        @XmlElement 
        public String version; 
    
        @XmlAnyElement
        public T data; 
    
        EnvelopeClass() { 
        } 
    
        EnvelopeClass(String version, T data) { 
            this.version = version; 
            this.data = data; 
        } 
    
    }
    

    DataClass

    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlRootElement;
    
    @XmlRootElement(name="data") 
    public class DataClass { 
    
        @XmlElement 
        public String name; 
    
        DataClass() { 
        } 
    
        DataClass(String name) { 
            this.name = name; 
        } 
    
    }
    

    Demo

    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.Marshaller;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            JAXBContext jc = JAXBContext.newInstance(EnvelopeClass.class);
    
            DataClass data = new DataClass("myName");
            EnvelopeClass envelope = new EnvelopeClass<DataClass>("1.0", data);
    
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(envelope, System.out);
        }
    }
    
    0 讨论(0)
提交回复
热议问题