Java HTML / XML How to - Map Generic Collections








Question

We would like to know how to map Generic Collections.

Answer

import java.util.Arrays;
import java.util.List;
//from  w  w  w .ja  v a2s  .co m
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

public class JAXBTest {

    @XmlRootElement
    public static class Root {
        private List<Person> friend;
        private List<Thing> stuff;

        @XmlElementWrapper(name="friends")
        public List<Person> getFriend() {
            return friend;
        }

        public void setFriend(List<Person> friend) {
            this.friend = friend;
        }

        @XmlElementWrapper(name="stuff")
        public List<Thing> getStuff() {
            return stuff;
        }

        public void setStuff(List<Thing> stuff) {
            this.stuff = stuff;
        }
    }

    public static class Person { 
        private String name; 

        public String getName() { 
            return name; 
        } 

        public void setName(String name) { 
            this.name = name; 
        } 
    }

    public static class Thing { 
        private String description; 

        public String getDescription() { 
            return description; 
        } 

        public void setDescription(String description) { 
            this.description = description; 
        }
    }

    public static void main(String[] args) throws JAXBException {
        JAXBContext jaxbContext = JAXBContext.newInstance(Root.class);
        Root root = new Root();

        Person fred = new Person();
        fred.setName("Fred");
        root.setFriend(Arrays.asList(fred));

        Thing xbox = new Thing();
        xbox.setDescription("Xbox 360");
        root.setStuff(Arrays.asList(xbox));

        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root, System.out);
    }

}