java - 序列化 Java 对象

标签 java xml jaxb

让我知道序列化我的 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 可以是很多东西,包括 OutputStreamWriterFile。如果您想将其作为 String 获取,请使用 StringWriter

关于java - 序列化 Java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6048530/

相关文章:

java - 如何在每个 Activity 中显示滑动菜单栏?

java - jaxb 解码列表不起作用

java - 如何使用 JAXB 在 Java 中解析这个 XML?

java - 如何使用restclient将字典传递到android中的Web服务?

java - 当我们允许使用Object类创建异构数组时,java中的数组如何能够是同构的?

python - 如何通过 XPath 选择一个 div 下的跨度而不是另一个 div 下的跨度?

java - 需要将我的 SOAP 请求与 SoapUI 发送的内容相匹配

具有隐藏和显示功能的 Java Swing 表单菜单

java - 在回调中渲染 http 响应

C#/.NET XML 序列化程序 - 使用属性作为元素名称