原文: 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 格式时,会发生此异常。 栈跟踪如下所示:

  1. Exception in thread "main" javax.xml.bind.JAXBException: class java.util.ArrayList nor any of its super class is known to this context.
  2. at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getBeanInfo(Unknown Source)
  3. at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsRoot(Unknown Source)
  4. at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(Unknown Source)
  5. at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.marshal(Unknown Source)
  6. at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(Unknown Source)
  7. at com.howtodoinjava.jaxb.examples.list.TestEmployeeMarshing.main(TestEmployeeMarshing.java:58)

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

随机异常

原因

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

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

解决方案:创建包装器类

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

  1. @XmlRootElement(name = "employees")
  2. @XmlAccessorType (XmlAccessType.FIELD)
  3. public class Employees
  4. {
  5. @XmlElement(name = "employee")
  6. private List<Employee> employees = null;
  7. public List<Employee> getEmployees() {
  8. return employees;
  9. }
  10. public void setEmployees(List<Employee> employees) {
  11. this.employees = employees;
  12. }
  13. }

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

  1. static Employees employees = new Employees();
  2. static
  3. {
  4. employees.setEmployees(new ArrayList<Employee>());
  5. Employee emp1 = new Employee();
  6. emp1.setId(1);
  7. emp1.setFirstName("Lokesh");
  8. emp1.setLastName("Gupta");
  9. emp1.setIncome(100.0);
  10. Employee emp2 = new Employee();
  11. emp2.setId(2);
  12. emp2.setFirstName("John");
  13. emp2.setLastName("Mclane");
  14. emp2.setIncome(200.0);
  15. employees.getEmployees().add(emp1);
  16. employees.getEmployees().add(emp2);
  17. }
  18. private static void marshalingExample() throws JAXBException
  19. {
  20. JAXBContext jaxbContext = JAXBContext.newInstance(Employees.class);
  21. Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
  22. jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  23. jaxbMarshaller.marshal(employees, System.out);
  24. }
  25. Output:
  26. <employees>
  27. <employee>
  28. <id>1</id>
  29. <firstName>Lokesh</firstName>
  30. <lastName>Gupta</lastName>
  31. <income>100.0</income>
  32. </employee>
  33. <employee>
  34. <id>2</id>
  35. <firstName>John</firstName>
  36. <lastName>Mclane</lastName>
  37. <income>200.0</income>
  38. </employee>
  39. </employees>

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

祝您学习愉快!