XML > JAXB > Avoid serialization using Transient annotation
Avoid serialization using Transient annotation
The following example shows restricting some properties from being
serialized using @XmlTransient annotation.
package com.bethecoder.tutorials.jaxb.common;
import java.util.Date;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
@XmlRootElement
@XmlAccessorType ( XmlAccessType.FIELD ) //Allows to get data through fields rather than public getter/setters
public class Student5 {
private String firstName;
private String lastName;
private int age;
@XmlTransient //Does'nt serialize transient properties to XML
private String hobby;
@XmlTransient //Does'nt serialize transient properties to XML
private Date dob;
/**
* NOTE : Should have a no-arg default constructor.
*/
public Student5 () {
}
public Student5 ( String firstName, String lastName, int age, String hobby,
Date dob ) {
super () ;
this .firstName = firstName;
this .lastName = lastName;
this .age = age;
this .hobby = hobby;
this .dob = dob;
}
public String getFirstName () {
return firstName;
}
public void setFirstName ( String firstName ) {
this .firstName = firstName;
}
public String getLastName () {
return lastName;
}
public void setLastName ( String lastName ) {
this .lastName = lastName;
}
public int getAge () {
return age;
}
public void setAge ( int age ) {
this .age = age;
}
public String getHobby () {
return hobby;
}
public void setHobby ( String hobby ) {
this .hobby = hobby;
}
public Date getDob () {
return dob;
}
public void setDob ( Date dob ) {
this .dob = dob;
}
}
package com.bethecoder.tutorials.jaxb.tests;
import java.util.Date;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import com.bethecoder.tutorials.jaxb.common.Student5;
public class Transient {
public static void main ( String [] args ) throws JAXBException {
Student5 student = new Student5 ( "Sriram" , "Kasireddi" , 2 , "Painting" , new Date ()) ;
/**
* Create JAXB Context from the classes to be serialized
*/
JAXBContext context = JAXBContext.newInstance ( Student5. class ) ;
Marshaller m = context.createMarshaller () ;
m.setProperty ( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE ) ;
m.marshal ( student, System.out ) ;
}
}
It gives the following output,