感谢Blaise Doughan和他的文章,我找到了解决方案。
首先,我们需要本文提供的Wrapper类:
@XmlRootElementpublic class Wrapper<T> { private List<T> items; public Wrapper() { items = new ArrayList<T>(); } public Wrapper(List<T> items) { this.items = items; } @XmlAnyElement(lax=true) public List<T> getItems() { return items; }}
然后,我修改了Response类以便使用它:
@XmlRootElement@XmlAccessorType(XmlAccessType.FIELD)public class Response<T> { @XmlElement protected String status; @XmlElement protected Wrapper<T> result; ... public Response(String status, List<T> result) { this.status = status; this.result = new Wrapper<>(result); } ... public List<T> getResult() { return result.getItems(); } ...}
最后是解组代码:
JAXBContext context = JAXBContext.newInstance(Response.class, Project.class, User.class, Wrapper.class);Unmarshaller unmarshaller = context.createUnmarshaller();StreamSource source = new StreamSource(new File("responseProject.xml"));Response<Project> responseProject = (Response<Project>)unmarshaller.unmarshal(source);System.out.println(responseProject.getStatus());for (Project project:responseProject.getResult()) System.out.println(project);source = new StreamSource(new File("responseUser.xml"));Response<User> responseUser = (Response<User>)unmarshaller.unmarshal(source);System.out.println(responseUser.getStatus());for (User user:responseUser.getResult()) System.out.println(user);
另外,您可以将此注释添加到Response类:
@XmlSeeAlso({Project.class, User.class})
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)