Why doesn't wrapping a List/Map in a JAXBElement work?

168 views Asked by At

At first, I was quite overjoyed when I found out about JAXBElement - it removed the necessity of annotating my model classes with @XmlRootElement. So, I was also hoping that I would not longer require a "Wrapper" class for my hashmap or list. But alas, marshaling a JAXBElement with the list/hashmap gives me an empty collection. Why doesn't this work? And isn't there a general way to handle collections? I might have to marshal many different types of collections, so writing a wrapper for each of them, will probably be too much.

Example code -

public static void main(String[] args) throws JAXBException, IOException {

    List<String> list = new ArrayList<String>();
    list.add("one");
    list.add("five");
    list.add("twentyone");
    list.add("seventytwo");

    Object data=list;
    Class dataClass= data.getClass();
    JAXBContext context = null;
    try {
        context = JAXBContext.newInstance(data.getClass());
    } catch (JAXBException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    String dataClassNameTemp = dataClass.getSimpleName();
    String firstLetter = dataClassNameTemp.substring(0, 1).toLowerCase();
    String dataClassName = firstLetter + dataClassNameTemp.substring(1);
    JAXBElement JAXBData = new JAXBElement(new QName(dataClassName),dataClass, data);
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

/*  m.marshal(data,System.out);*/
    m.marshal(JAXBData, System.out);
    File file = new File("/home/aneeshb/exp/map1.xml");
    FileWriter fw = new FileWriter(file);
    m.marshal(JAXBData, fw);

}

Output -

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<arrayList/>
0

There are 0 answers