markiz
markiz

Reputation: 2184

Exception converting object to XML using jaxb

I am trying to build an XML from object using JAXB.

But I am missing something because I get an exception:

javax.xml.bind.MarshalException - with linked exception: [com.sun.istack.internal.SAXException2: class Employee nor any of its super class is known to this context. javax.xml.bind.JAXBException: class Employee nor any of its super class is known to this context.]

@XmlRootElement(name = "employee")
public class Employee {
    private String name;
    private String employeeId;  

    public String getName() {
        return name;
    }

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

    public void setEmployeeId(String employeeId) {
        this.employeeId = employeeId;
    }

}

@XmlRootElement(name = "Data")
public class Data {
    public Data() {
    }

    private List employees;

    @XmlElementWrapper(name = "employeeList")
    @XmlElement(name = "employee")
    public List getEmployees() {
        return employees;
    }

    public void setEmployees(List employees) {
        this.employees = employees;
    }

}


public static void main(String[] args) {
        ArrayList list = new ArrayList();

        Employee e1 = new Employee();
        e1.setName("Name");
        e1.setEmployeeId("1");
        list.add(e1);
        Data data = new Data();
        data.setEmployees(list);

        JAXBContext context;

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();

        try {
            context = JAXBContext.newInstance(Data.class);
            Marshaller m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.marshal(data, outStream);
        } catch (JAXBException e) {

            e.printStackTrace();
        }

    }

Upvotes: 3

Views: 4680

Answers (1)

bdoughan
bdoughan

Reputation: 148977

You need to do one of the following so that your JAXB (JSR-222) implementation is aware that the employees property on your Data class contains instances of Employee.

@XmlElementWrapper(name = "employeeList")
@XmlElement(name = "employee", type=Employee.class)
public List getEmployees() {
    return employees;
}

or

@XmlElementWrapper(name = "employeeList")
@XmlElement(name = "employee")
public List<Employee> getEmployees() {
    return employees;
}

Upvotes: 4

Related Questions