我使用Spring和JAXB,并且想要封送不同DTO对象的列表,因此 所需的XML响应应类似于:
<root>
<dto_list>
<dto1>
<name>xxx</name>
</dto1>
<dto2>
<location>xxx</location>
</dto2>
</dto_list>
</root>
假定类对象为:
@XmlRootElement(name = "Dto1")
@XmlAccessorType(XmlAccessType.NONE)
public class Dto1 {
@XmlElement
private String name;
// setter/getters
}
和
@XmlRootElement(name = "Dto2")
@XmlAccessorType(XmlAccessType.NONE)
public class Dto2 {
@XmlElement
private String location;
// setter/getters
}
和包装器类:
@XmlRootElement(name = "root")
@XmlAccessorType(XmlAccessType.NONE)
public class DTOsWrapper {
private List<Object> dto;
public void setDto(List<Object> dto) {
this.dto = dto;
}
@XmlElementWrapper(name = "dto_list")
@XmlElements({
@XmlElement(name = "dto1", type = Dto1.class),
@XmlElement(name = "dto2", type = Dto2.class)
})
public List<Object> getDto() {
return dto;
}
}
和端点:
@RestController
public class DTOEndpoint {
@Autowired
private IDTOService service;
@RequestMapping(value = "/restxml", produces = "application/xml")
public Object retrieveAllDTOs() {
DTOsWrapper o = service.findDtos(); //returns a DTOsWrapper obj of a list containing Dto objs, i.e Dto1, Dto2 etc
return o;
}
我收到{“错误”:“ org.springframework.http.converter.HttpMessageConversionException:无法实例化类[class <> to.DTOsWrapper]的JAXBContext:1个IllegalAnnotationExceptions计数;有人知道吗?