Marshalling is a technique that can be easily understood and utilized efficiently. It is the process of converting a POJO(Plain Old Java Object) in memory into a format that can be written to disk or send via network, usually in text formats like xml or json. The reverse of this technique is called unmarshalling.
Difference between Marshalling and Serialization:
Marshalling is similar to Serialization in practice but the difference is that, Marshalling also saves the code of an object in addition to its state.
Example
In the following example to explain marshalling, standard JAXB(Java Architecture for XML Binding) is used. For marshalling an object using JAXB, it must have annotation for the root element - @XmlRootElement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package blog.warfox.tutorials.marshalling;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Student class for Marshalling demo example
* @author warfox
*/
@XmlRootElement(name="student")
publicclassStudent{
private String name;
privateint rollNo;
privatedouble marks;
privateint rank;
public String getName(){
returnthis.name;
}
publicvoidsetName(String name){
this.name = name;
}
publicintgetRollNo(){
returnthis.rollNo;
}
publicvoidsetRollNo(int rollNo){
this.rollNo = rollNo;
}
publicdoublegetMarks(){
returnthis.marks;
}
publicvoidsetMarks(double marks){
this.marks = marks;
}
publicintgetRank(){
returnthis.rank;
}
publicvoidsetRank(int rank){
this.rank = rank;
}
}
Marshaller class which does the marshalling job
An instance of student is created and given for marshalling.
In the above example, JAXB has automatically copied the xml tags from the property names of Student class. We can set our own tag names by using JAXB’s @XmlElement annotation on the access method as follows.