我有以下 xml 字符串。我想将它转换成一个 java 对象,将每个标签映射到该对象的字段。如果我可以引入与标签名称不同的字段名称,那就更好了。我该怎么做?我正在查看 JAXB,但我仍然对“ns4:response”和标签中的标签等部分感到困惑。提前谢谢你...
<ns4:response>
<count>1</count>
<limit>1</limit>
<offset>1</offset>
<ns3:payload xsi:type="productsPayload">
<products>
<product>
<avgRating xsi:nil="true"/>
<brand>Candie's</brand>
<description>
<longDescription>
long descriptions
</longDescription>
<shortDescription>
short description
</shortDescription>
</description>
<images>
<image>
<altText>alternate text</altText>
<height>180.0</height>
<url>
url
</url>
<width>180.0</width>
</image>
</images>
<price>
<clearancePrice xsi:nil="true"/>
<regularPrice xsi:nil="true"/>
<salePrice>28.0</salePrice>
</price>
</product>
</products>
</ns3:payload>
</ns4:response>
最佳答案
JAXB 是用于将对象与 XML 相互转换的 Java 标准 ( JSR-222 )。以下内容应该有所帮助:
从字符串解码
在 JAXB impl 可以解码之前,您需要将 String
包装在 StringReader
的实例中。
StringReader sr = new StringReader(xmlString);
JAXBContext jaxbContext = JAXBContext.newInstance(Response.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Response response = (Response) unmarshaller.unmarshal(sr);
不同的字段和 XML 名称
您可以使用 @XmlElement
注释来指定您想要的元素名称。默认情况下,JAXB 查看属性。如果您希望基于字段的映射,则需要设置 @XmlAccessorType(XmlAccessType.FIELD)
。
@XmlElement(name="count")
private int size;
命名空间
@XmlRootElement
和 @XmlElement
注释还允许您在需要时指定 namespace 限定条件。
@XmlRootElement(namespace="http://www.example.com")
public class Response {
}
了解更多信息
关于java - 将 xml 字符串转换为 Java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11896801/