让我知道序列化我的 Java 对象下载的最佳方法。这是通过 WSDL 的 java wsimport 工具生成的类。
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Download", propOrder = {
"Response",
"VendorInformation",
"DownloadItem",
"DownloadCommentItem",
"DownloadIntercomItem"
})
public class Download
{
@XmlElement(name = "Response")
protected ResponseMessageManagementType Response;
@XmlElement(name = "VendorInformation")
protected DownloadVendorInformation VendorInformation;
@XmlElement(name = "DownloadItem")
protected List<DownloadDownloadItem> DownloadItem;
@XmlElement(name = "DownloadCommentItem")
protected ArrayOfDownloadDldComment DownloadCommentItem;
@XmlElement(name = "DownloadIntercomItem")
protected ArrayOfDownloadDldIntercom DownloadIntercomItem;
.........................
}
从该工具生成的 java 类没有任何序列化实现。 我想按照这种格式序列化 Download 类:
<?xml version="1.0" encoding="utf-8"?>
<Download xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="HTTP://xyz.abc.Com//Vendor/DownloadWSE.xsd">
<Response>
.....
</Response>
<VendorInformation>
...............
</VendorInformation>
<DownloadItem>
<DownloadDownloadItem>
.......
</DownloadDownloadItem>
<DownloadDownloadItem>
.......
</DownloadDownloadItem>
<DownloadDownloadItem>
.......
</DownloadDownloadItem>
</DownloadItem>
<DownloadCommentItem>
........
</DownloadCommentItem>
<DownloadIntercomItem>
........
</DownloadIntercomItem>
</Download>
您可以看到 XmlElementName 和 XML 字符串内容之间的映射。 我不知道如何做到这一点。
谢谢
最佳答案
这是JAXB 。您需要:
JAXBContext ctx = JAXBConetxt.newInstance(Download.class);
Marshaller m = ctx.createMarshaller();
m.marshal(downloadObject, out);
其中 out
可以是很多东西,包括 OutputStream
、Writer
和 File
。如果您想将其作为 String
获取,请使用 StringWriter
关于java - 序列化 Java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6048530/