Deserialization in Java

Deserialization in Java can be defined as the process to get the object back from the serialized form.In the last post, Serialization in Java we have serialized the Student object.In this post, we are going to Deserialize the same Student Object.

Student.java

package com.javainstance;
JavaInstance
import java.io.Serializable;

/**
 * @author javainstance
 *
 */
public class Student implements Serializable {

private int StudentId;

private String StudentName;

private int studentAge;

public Student(int studentId, String studentName, int studentAge) {
super();
StudentId = studentId;
StudentName = studentName;
this.studentAge = studentAge;
}

public int getStudentId() {
return StudentId;
}

public void setStudentId(int studentId) {
StudentId = studentId;
}

public String getStudentName() {
return StudentName;
}

public void setStudentName(String studentName) {
StudentName = studentName;
}

public int getStudentAge() {
return studentAge;
}

public void setStudentAge(int studentAge) {
this.studentAge = studentAge;
}

@Override
public String toString() {
return "Student [StudentId=" + StudentId + ", StudentName=" + StudentName + ", studentAge=" + studentAge + "]";
}

}

DeSerializationInJava.java

package com.javainstance;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DeSerializationInJava {


public static void main(String[] args) {
Student student=null;
try {
FileInputStream fileInputStream=new FileInputStream("D:\\Student.txt");
ObjectInputStream objectInputStream=new ObjectInputStream(fileInputStream);
student=(Student) objectInputStream.readObject();
objectInputStream.close();
fileInputStream.close();
System.out.println("Deserialization Successfull!");

System.out.println(student);

} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


}


Student.txt

¬í sr com.javainstance.Studentù ‚R(L I  StudentIdI 
studentAgeL StudentNamet Ljava/lang/String;xp     t James

Output:

Deserialization Successful!
Student [StudentId=1, StudentName=James, studentAge=21]

References:
https://docs.oracle.com/javase/tutorial/jndi/objects/serial.html


Give you suggestion in comments.If you like the post Share with your friends on social network.


You may be interested in:  Convert Java Object to JSON.






Deserialization in Java Deserialization in Java Reviewed by JavaInstance on 10:03:00 AM Rating: 5

No comments:

Powered by Blogger.