JAXBException: class java.util.ArrayList nor any of its super class is known to this context
This exception occurs when you are using JAXB to marshal a Java object (collection type) to xml format. The stack trace looks like this: 1. Reason The above exception occurs because JAXB always expects a @XmlRootElement annotation on the entity, it gets to marshal. This is mandatory and …
This exception occurs when you are using JAXB to marshal a Java object (collection type) to xml format. The stack trace looks like this:
Exception in thread "main"jakarta.xml.bind.JAXBException: class java.util.ArrayList nor any of its super class is known to this context.at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getBeanInfo(Unknown Source)at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsRoot(Unknown Source)at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(Unknown Source)at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.marshal(Unknown Source)at jakarta.xml.bind.helpers.AbstractMarshallerImpl.marshal(Unknown Source)at com.howtodoinjava.jaxb.examples.list.TestEmployeeMarshing.main(TestEmployeeMarshing.java:58)
Random exceptions
1. Reason
The above exception occurs because JAXB always expects a @XmlRootElement annotation on the entity, it gets to marshal. This is mandatory and can not be skipped. This @XmlRootElement annotation is required to get metadata from the root element of XML marshalled from a Java object.
ArrayList class OR any java collection class does not have any JAXB annotations on it. Due to this JAXB is unable to parse any such java objects and raises this error.
2. The solution is to a Create Wrapper Class
This is a recommended approach because it gives you the flexibility to add/remove fields in the future e.g. size attribute.
Employees employees =newEmployees();//Add the employees in listEmployee emp1 =newEmployee(1,"Lokesh","Gupta",null,null);Employee emp2 =newEmployee(1,"John","McLean",null,null);
employees.getEmployees().add(emp1);
employees.getEmployees().add(emp2);//Write to XMLJAXBContext jaxbContext =JAXBContext.newInstance(Employees.class);Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);//Marshal the employees list in console
jaxbMarshaller.marshal(employees,System.out);//Marshal the employees list in file
jaxbMarshaller.marshal(employees,newFile("out.xml"));
A fun-loving family man, passionate about computers and problem-solving, with over 15 years of experience in Java and related technologies.
An avid Sci-Fi movie enthusiast and a fan of Christopher Nolan and Quentin Tarantino.
Comments