如何使用JAXB将ArrayList <object>转换为XML?</object>

时间:2012-08-27 10:11:29

标签: java xml jaxb

我正在尝试使用JAXB将ArrayList转换为xml ..

ArrayList<LDAPUser> myList = new ArrayList<LDAPUser>();

    myList = retrieveUserAttributes.getUserBasicAttributes(lastName,
            retrieveUserAttributes.getLdapContext());



    JAXBContext jaxbContext = JAXBContext.newInstance(LDAPUser.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

    StringWriter sw = new StringWriter();

    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

     jaxbMarshaller.marshal(myList, sw);
     System.out.println(sw.toString());     
     return sw.toString();

... 但它没有用,我收到了这个错误:

  

27-Aug-2012 10:43:58 org.apache.catalina.core.StandardWrapperValve   在上下文中调用SEVERE:servlet [spring]的Servlet.service()   path [/ Spring3-LDAP-WebService]抛出异常[请求处理   失败;嵌套异常是javax.xml.bind.JAXBException:类   java.util.ArrayList也不知道它的任何超类   context。]带有根本原因javax.xml.bind.JAXBException:class   java.util.ArrayList也不知道它的任何超类   上下文。 at   com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getBeanInfo(JAXBContextImpl.java:554)     在   com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:470)     在   com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:314)     在   com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:243)     在   javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:96)     在   ie.revenue.spring.RestController.searchLdapUsersByLastNameTwo(RestController.java:69)     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at   sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)...........

请帮忙! 感谢。

1 个答案:

答案 0 :(得分:4)

尝试创建一个包装列表并使其成为xml根的类,例如:

@XmlRootElement
class LDAPUsers {
    private List<LDAPUser> users;
    ... get ... set ... constructor 
}

然后封送LDAPUsers对象。