javax.xml.bind.UnmarshalException: 意外的元素 (uri:"", local:"xml")。所需元素为(none)
将xml转换为object时候报错:javax.xml.bind.UnmarshalException: 意外的元素 (uri:"", local:"xml")。所需元素为(none)
代码如下:
/** * xml转object * @param clazz * @param xml * @param <T> * @return */ public static <T> T xmlToObject(Class<T> clazz, String xml) { try { JAXBContext jaxbContext = JAXBContext.newInstance(clazz); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); StringReader reader = new StringReader(xml); T message = (T) unmarshaller.unmarshal(reader); return message; } catch (JAXBException e) { e.printStackTrace(); } }
调用方:
WxMessage wxMessage = XmlUtils.xmlToObject(WxMessage.class, requestBody);
原因:通过Unmarshaller 根据xml反射为对象
解决:在WxMessage,需要加上xml的注解:@XmlRootElement(name="xml")