Java 在ArrayList上的JAXBElement?

Java 在ArrayList上的JAXBElement?,java,jaxb,marshalling,Java,Jaxb,Marshalling,如何整理一份清单 我有一个POJO无法注释,例如: public class APojo { private String aString; public APojo() { super(); } public String getAString() { return aString; } public void setAString(String aString) { this.aString = aString; } } 所以我要这么做 APojo aP

如何整理一份清单

我有一个POJO无法注释,例如:

public class APojo {

private String aString;

public APojo() { 
    super(); 
}

public String getAString() {
    return aString;
}

public void setAString(String aString) {
    this.aString = aString;
}
}
所以我要这么做

APojo aPojo = new APojo();
aPojo.setaString("a string");       
JAXBElement<APojo> aJAXBedPojo = new JAXBElement<APojo>(new QName("apojo"), APojo.class, aPojo);
JAXBContext context = JAXBContext.newInstance(APojo.class, ArrayList.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(list, System.out);
运行时将引发:

[com.sun.istack.internal.SAXException2: unable to marshal type "java.util.ArrayList" as an element because it is missing an @XmlRootElement annotation]
这是正常的,因为ArrayList没有注释

我知道我可以围绕ArrayList创建一个包装器,并用@XmlRootElement对其进行注释,这样我就可以整理这个包装器


我正在寻找一种没有这种包装的解决方案。是否可以使用T作为ArrayList创建JAXbeElement?还是类似的?

我强烈建议您使用。您只需向封送拆收器注册适配器,它将使用带注释的适配器类代替无法注释的类

另外,我认为一个包装器类会比尝试在没有包装器的情况下做一些事情更干净

也就是说,如果你真的想,你可以尝试以下方法:

List<JAXBElement<APojo>> list = new ArrayList<JAXBElement<APojo>>();
JAXBElement<List<JAXBElement<APojo>>> listElement = new JAXBElement<List<JAXBElement<APojo>>>(new QName("apojolist"), List.class, list);
List List=new ArrayList();
JAXBElement-liselement=newjaxbelement(newqname(“apojolist”),List.class,List);

最好的解决方案似乎是构建一个如所解释的那样的包装器

由于我的目标是从REST web服务返回列表,因此将列表封装在

new GenericEntity<List<APojo>>(aPojo) {}
newgenericentity(aPojo){

有什么理由不能使用xsd创建您需要的任何/所有jaxb绑定吗?有一个:我想了解如何手动创建:)事实上,我已经尝试过了,但Eclipse告诉我“构造函数JAXBElement(QName、Class、List)未定义”。我不清楚为什么:)正确的代码必须非常接近你的答案,但我没有找到它:(
new GenericEntity<List<APojo>>(aPojo) {}