JAXB: How should I marshal complex nested data structures?

后端 未结 6 1196
无人及你
无人及你 2020-11-27 02:27

I have several complex data structures like

Map< A, Set< B > >
Set< Map< A, B > >
Set< Map< A, Set< B > > >
Map<         


        
6条回答
  •  一向
    一向 (楼主)
    2020-11-27 03:05

    Here is my marshaller/unmarshaller for the list of @XmlType class.

    E.g

    //Type to marshall
    @XmlType(name = "TimecardForm", propOrder = {
    "trackId",
    "formId"
    }) 
    public class TimecardForm {
    
        protected long trackId;
        protected long formId;
        ...
    }
    
    //a list holder
    @XmlRootElement
    public class ListHodler {
        @XmlElement
        private List value ;
    
        public ListHodler() {
        }
    
        public ListHodler(List value) {
            this.value = value;
        }
    
        public List getValue() {
            if(value == null)
                value = new ArrayList();
            return this.value;
        }
    }
    
    //marshall collection of T
    public static  void marshallXmlTypeCollection(List value,
            Class clzz, OutputStream os) {
        try {
            ListHodler holder = new ListHodler(value);
            JAXBContext context = JAXBContext.newInstance(clzz,
                    ListHodler.class);
            Marshaller m = context.createMarshaller();
            m.setProperty("jaxb.formatted.output", true);
    
            m.marshal(holder, os);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
    
    //unmarshall collection of T
    @SuppressWarnings("unchecked")
    public static  List unmarshallXmlTypeCollection(Class clzz,
            InputStream input) {
        try {
            JAXBContext context = JAXBContext.newInstance(ListHodler.class, clzz);
            Unmarshaller u = context.createUnmarshaller();
    
            ListHodler holder = (ListHodler) u.unmarshal(new StreamSource(input));
    
            return holder.getValue();
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    
        return null;
    }
    

提交回复
热议问题