[已解决]:javax.xml.bind.JAXBException:java.util.ArrayList或其任何超类不是此上下文的已知类

[已解决]:javax.xml.bind.JAXBExceptionjava.util.ArrayList或其任何超类不是此上下文的已知类

原文: https://howtodoinjava.com/jaxb/solved-javax-xml-bind-jaxbexception-class-java-util-arraylist-nor-any-of-its-super-class-is-known-to-this-context/

当您使用 JAXB 将 Java 对象(集合类型)编组为 xml 格式时,会发生此异常。 栈跟踪如下所示:

Exception in thread "main" javax.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 javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(Unknown Source)
	at com.howtodoinjava.jaxb.examples.list.TestEmployeeMarshing.main(TestEmployeeMarshing.java:58)

Random exceptions

随机异常

原因

发生上述异常是因为 JAXB 总是期望实体上有一个@XmlRootElement注解,它会编组。 这是强制性的,不能跳过。 需要@XmlRootElement注解才能从 Java 对象编组的 XML 根元素中获取元数据。

ArrayList类或任何 Java 集合类都没有任何 JAXB 注解。 由于这个原因,JAXB 无法解析任何此类 java 对象,并引发此错误。

解决方案:创建包装器类

建议您使用此方法,因为它可以让您灵活地在将来(例如)添加/删除字段大小属性。

@XmlRootElement(name = "employees")
@XmlAccessorType (XmlAccessType.FIELD)
public class Employees 
{
	@XmlElement(name = "employee")
	private List<Employee> employees = null;

	public List<Employee> getEmployees() {
		return employees;
	}

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

现在,您可以按以下方式使用此类:

static Employees employees = new Employees();

static 
{
	employees.setEmployees(new ArrayList<Employee>());

	Employee emp1 = new Employee();
	emp1.setId(1);
	emp1.setFirstName("Lokesh");
	emp1.setLastName("Gupta");
	emp1.setIncome(100.0);

	Employee emp2 = new Employee();
	emp2.setId(2);
	emp2.setFirstName("John");
	emp2.setLastName("Mclane");
	emp2.setIncome(200.0);

	employees.getEmployees().add(emp1);
	employees.getEmployees().add(emp2);
}

private static void marshalingExample() throws JAXBException
{
	JAXBContext jaxbContext = JAXBContext.newInstance(Employees.class);
	Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

	jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

	jaxbMarshaller.marshal(employees, System.out);
}

Output:

<employees>
    <employee>
        <id>1</id>
        <firstName>Lokesh</firstName>
        <lastName>Gupta</lastName>
        <income>100.0</income>
    </employee>
    <employee>
        <id>2</id>
        <firstName>John</firstName>
        <lastName>Mclane</lastName>
        <income>200.0</income>
    </employee>
</employees>

请参阅此帖子中的完整示例: java ArrayListSet编组示例

祝您学习愉快!