java - 无法将 XML 字符串转换为 Java 对象
问题描述
我正在尝试将 XML 字符串解组为 Java 对象。但我无法做到。我的回应是空的。寻求帮助。在网上尝试了很多东西。
private static void unmarshallStringToObj(String xmlString) throws JAXBException {
StringReader sr = new StringReader(xmlString);
JAXBContext jaxbContext = JAXBContext.newInstance(ApiResponse.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
ApiResponse response = (ApiResponse) unmarshaller.unmarshal(sr);
System.out.println(response);
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "ERROR")
public class ApiResponse {
@XmlElement(name = "ERROR")
private String ERROR;
// getters and setters and constructors
这是输入 XML 字符串
<ERROR>The specified engine does not exist!</ERROR>
这是控制台中的输出
ApiResponse [ERROR=null]
解决方案
@XmlRootElement(name="ERROR")
public class ErrorString {
@XmlValue
String value;
}
JAXBContext jbContext = JAXBContext.newInstance(ErrorString.class);
ErrorString myString = (ErrorString) jbContext.createUnmarshaller().unmarshal(...);
尝试以这种方式获取 XML 元素,它将起作用。