JAVA serialization and deserialization (default format, XML format, JSON format)

Source: Internet
Author: User

What is serialization?
The serialization mechanism in java can write the status information of an instance object to a byte stream, so that it can be transmitted through socket or stored persistently in a database or file system; then, you can reconstruct an object based on the information in the byte stream as needed. Serialization mechanism is widely used in java, and EJB, RMI, and other technologies are based on this.

Correct use of serialization Mechanism
In general, to make a class Serializable, you only need to simply implement the java. io. Serializable interface (and also implement the construction method without parameters ). This interface is a markup interface that does not contain any content. If this interface is implemented, this class is ready to support serialization. The following example defines the class Person and declares that it can be serialized.

[Java]
Public class Person implements Serializable {
 
Private static final long serialVersionUID = 1L;

Private String name ;;
Private int age;
Public Person (){

}
Public Person (String str, int n ){
System. out. println ("Inside Person's Constructor ");
Name = str;
Age = n;
}
Public String getName (){
Return name;
}
Public int getAge (){
Return age;
}
}


The following code converts three formats:

1. Default format.

[Java]
Public class SerializeToFlatFile {
Public static void main (String [] args ){
SerializeToFlatFile ser = new SerializeToFlatFile ();
Ser. savePerson ();
Ser. restorePerson ();
}

Public void savePerson (){
Person myPerson = new Person ("Jay", 24 );
Try {
FileOutputStream fos = new FileOutputStream ("E: \ person.txt ");
ObjectOutputStream oos = new ObjectOutputStream (fos );
System. out. println ("Person -- Jay, 24 --- Written ");

Oos. writeObject (myPerson );
Oos. flush ();
Oos. close ();
} Catch (Exception e ){
E. printStackTrace ();
}
}

@ SuppressWarnings ("resource ")
Public void restorePerson (){
Try {
FileInputStream fls = new FileInputStream ("E: \ person.txt ");
ObjectInputStream ois = new ObjectInputStream (fls );

Person myPerson = (Person) ois. readObject ();
System. out. println ("\ n --------------------- \ n ");
System. out. println ("Person -- read :");
System. out. println ("Name is:" + myPerson. getName ());
System. out. println ("Age is:" + myPerson. getAge ());

} Catch (Exception e ){
E. printStackTrace ();
}
}
}
Output result: sr test. serializable. Person I ageL namet Ljava/lang/String; xp t Jay


2. XML format

[Java]
// Reference: http://www.cnblogs.com/bluesky5304/archive/2010/04/07/1706061.html
Public class SerializeXML {
 
Public static void main (String [] args ){
SerializeXML ser = new SerializeXML ();
Ser. serializeToXml ();
Ser. deSerializeFromXml ();
}
Public void serializeToXml (){
Person [] myPersons = new Person [2];
MyPersons [0] = new Person ("Jay", 24 );
MyPersons [1] = new Person ("Tom", 23 );

XStream xStream = new XStream ();
XStream. alias ("Person", Person. class );
Try {
FileOutputStream foStream = new FileOutputStream ("E: \ persons. xml ");
XStream. toXML (myPersons, foStream );
} Catch (Exception e ){
E. printStackTrace ();
}
}
Public void deSerializeFromXml (){
XStream xStream = new XStream ();
XStream. alias ("Person", Person. class );
Person [] myPersons = null;
Try {
FileInputStream flStream = new FileInputStream ("E: \ persons. xml ");
MyPersons = (Person []) xStream. fromXML (flStream );
If (myPersons! = Null ){
For (Person person: myPersons ){
System. out. println (person. getName ());
System. out. println (person. getAge ());
}
}
} Catch (Exception e ){
E. printStackTrace ();
}
}
}
Output result:

[Html]
<Person-array>
<Person>
<Name> Jay </name>
<Age> 24 </age>
</Person>
<Person>
<Name> Tom </name>
<Age> 23 </age>
</Person>
</Person-array>

3. JSON format
[Java]
// Reference: http://www.cnblogs.com/hoojo/archive/2011/04/22/2025197.html
Public class SerializeJSON {
 
Public static void main (String [] args ){
SerializeJSON serializeJSON = new SerializeJSON ();
SerializeJSON. writeJSON ();
SerializeJSON. readJSON ();
}
 
Public void writeJSON (){
XStream xStream = new XStream (new JettisonMappedXmlDriver ());
Person person = new Person ("geniushehe", 16 );
Try {
FileOutputStream fos = new FileOutputStream ("E: \ json. js ");
XStream. setMode (XStream. NO_REFERENCES );
XStream. alias ("Person", Person. class );
XStream. toXML (person, fos );
} Catch (FileNotFoundException e ){
E. printStackTrace ();
}
}
Public void readJSON (){
XStream xStream = new XStream (new JettisonMappedXmlDriver ());
Person person = null;
Try {
FileInputStream FCM = new FileInputStream ("E: \ json. js ");
XStream. setMode (XStream. NO_REFERENCES );
XStream. alias ("Person", Person. class );
Person = (Person) xStream. fromXML (SOx );
System. out. println (person. getName ());
System. out. println (person. getAge ());
} Catch (FileNotFoundException e ){
E. printStackTrace ();
}
} Www.2cto.com
}

Output result:
[Javascript]
{"Person": {"name": "geniushehe", "age": 16 }}

Author: isea533
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.