簡體   English   中英

從序列化中排除一些對象字段

[英]Excluding some Object fields from serialization

我正在使用javax.xml.bind.annotation.XmlRootElement注釋對象將其序列化為xml字符串。

        JAXBContext jc = JAXBContext.newInstance(obj.getClass());
        // Marshal the object to a StringWriter
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.example.com/schema.xsd");
        StringWriter stringWriter = new StringWriter();
        marshaller.marshal(obj, stringWriter);
        result = stringWriter.toString();

如何排除對象的某些字段以便不發送它們? 為了將其從最終字符串中排除,必須對類字段的注釋進行注釋。

使用@XmlTransient批注:

防止將JavaBean屬性/類型映射到XML表示形式。

@XmlTransient
public String toBeSkippedField;

您可以使用transient關鍵字來忽略要序列化的字段。

例如:

int k;
transient int j;

Variable j將不會被序列化,因為我們已經提到了transient關鍵字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM