简体   繁体   English

从序列化中排除一些对象字段

[英]Excluding some Object fields from serialization

I am using javax.xml.bind.annotation.XmlRootElement annotated object to serialize it into xml string. 我正在使用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();

How to exclude some fields of the object in order not to send them? 如何排除对象的某些字段以便不发送它们? What annotation that class field has to be annotated in order to exclude it from final string. 为了将其从最终字符串中排除,必须对类字段的注释进行注释。

Use the @XmlTransient annotation: 使用@XmlTransient批注:

Prevents the mapping of a JavaBean property/type to XML representation. 防止将JavaBean属性/类型映射到XML表示形式。

@XmlTransient
public String toBeSkippedField;

You could use the transient keyword to omit a field from being serialized. 您可以使用transient关键字来忽略要序列化的字段。

For example: 例如:

int k;
transient int j;

Variable j will not be serialized as we have mentioned the transient keyword. Variable j将不会被序列化,因为我们已经提到了transient关键字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM