我试图将字符串 XML 解码为 POJO 对象,但没有成功。这是我正在使用的代码
MyObject myobject = JAXB.unmarshal(new StringReader(myxmlstring), MyObject.class);
Xml 的结构和对象的结构如下:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:SomePerson xmlns:ns2="http://to/something">
<SomePerson>
<person>
<name>joe</name>
</person>
</SomePerson>
</ns2:SomePerson>
这是我的对象:
@XmlRootElement(name="SomePerson")
@XmlAccessorType(XmlAccessType.FIELD)
public class MyObject {
@XmlElement(name = "name")
private String name;
//getter and setters
}
最佳答案
建议你做这样的事情::
final DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final InputSource is = new InputSource();
is.setCharacterStream(new StringReader("<root><node1></node1></root>")); // put your xml string here
final Document doc = db.parse(is);
final XMLInputFactory xif = XMLInputFactory.newFactory();
final DOMSource domSource = new DOMSource(document);
final XMLStreamReader xsr = xif.createXMLStreamReader(domSource);
final XMLReaderWithoutNamespace xr = new XMLReaderWithoutNamespace(xsr);
final Unmarshaller unmarshaller = JAXBContext
.newInstance("POJO LOCATION").createUnmarshaller();
return (POJOClass) unmarshaller.unmarshal(xr);
请告诉我这是否有帮助
关于java - 使用 JAXB 解码字符串 XML 不起作用并仅返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60244740/