简体   繁体   中英

Excluding some Object fields from serialization

I am using javax.xml.bind.annotation.XmlRootElement annotated object to serialize it into xml string.

        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:

Prevents the mapping of a JavaBean property/type to XML representation.

@XmlTransient
public String toBeSkippedField;

You could use the transient keyword to omit a field from being serialized.

For example:

int k;
transient int j;

Variable j will not be serialized as we have mentioned the transient keyword.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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