3 回答

TA贡献1824条经验 获得超8个赞
我使用@LiorH的示例并将其扩展为:
@XmlRootElement(name="List")
public class JaxbList<T>{
protected List<T> list;
public JaxbList(){}
public JaxbList(List<T> list){
this.list=list;
}
@XmlElement(name="Item")
public List<T> getList(){
return list;
}
}
注意,它使用泛型,因此您可以将其与String之外的其他类一起使用。现在,应用程序代码很简单:
@GET
@Path("/test2")
public JaxbList test2(){
List list=new Vector();
list.add("a");
list.add("b");
return new JaxbList(list);
}
为什么JAXB包中不存在这个简单的类?有人在其他地方看到类似的东西吗?

TA贡献1786条经验 获得超11个赞
@GET
@Path("/test2")
public Response test2(){
List<String> list=new Vector<String>();
list.add("a");
list.add("b");
final GenericEntity<List<String>> entity = new GenericEntity<List<String>>(list) { };
return Respon

TA贡献1784条经验 获得超2个赞
如果任何人都想为包含多个类的元素的列表编写列表包装器,并且想要根据类类型给出单独的XmlElement名称而无需编写X Wrapper类,则可以使用@XmlMixed注释。这样,JAXB将根据设置的值来命名列表中的项目@XmlRootElement。这样做时,您必须使用以下命令指定可能在列表中的类@XmlSeeAlso
例:
列表中可能的类
@XmlRootElement(name="user")
public class User {/*...*/}
@XmlRootElement(name="entry")
public class LogEntry {/*...*/}
包装类
@XmlRootElement(name="records")
@XmlSeeAlso({User.class, LogEntry.class})
public static class JaxbList<T>{
protected List<T> records;
public JaxbList(){}
public JaxbList(List<T> list){
this.records=list;
}
@XmlMixed
public List<T> getRecords(){
return records;
}
}
例:
List l = new List();
l.add(new User("userA"));
l.add(new LogEntry(new UserB()));
XStream xStream = new XStream();
String result = xStream.toXML(l);
结果:
<records>
<user>...</user>
<entry>...</entry>
</records>
另外,您可以使用@XmlElementRef注解在包装类中直接指定XmlElement名称。
@XmlRootElement(name="records")
@XmlSeeAlso({User.class, LogEntry.class})
public static class JaxbList<T>{
protected List<T> records;
public JaxbList(){}
public JaxbList(List<T> list){
this.records=list;
}
@XmlElementRefs({
@XmlElementRef(name="item", type=Object.class),
@XmlElementRef(name="user", type=User.class),
@XmlElementRef(name="entry", type=LogEntry.class)
})
public List<T> getRecords(){
return records;
}
}
添加回答
举报