I want to serialize a POJO in the name value string format in a file. And when I read back the string I want the POJO back. I can only think of implementing the writeReplace() and readResolve() methods for this custom serialization. Is there any other/better way to do this?
Suppose my POJO is like this
class myPOJO(){
private String attribute1;
private String attribute2;
public myPOJO(String value1, String value2){
attribute1 = value1;
attribute2 = value2;
}
public String getAttribute1(){
return attribute1;
}
public void setAttribute1(String value){
attribute1 = value;
}
public String getAttribute2(){
return attribute2;
}
public void setAttribute2(String value){
attribute2 = value;
}
}
So I want this to be serialized in string format as
{attribute1:value1;attribute2:value2}
For custom java serialization, You should look at overriding readObject() and writeObject() Method. If these methods are overridden, Serialization api invokes these instead of doing default Serialization. readResolve() and writeReplace() methods have different usage e.g. when you are serializing singletons you need readResolve() to deserialize. Refer to following real life example from JDK (arrayList)
However if you POJO's physical representation is same as logical representation, then you can also go with default serialization w/o any issues.
To your above POJO, you can perform serialization in following way
class myPOJO implements Serializable{
private static final long serialVersionUID = 8683452581122892189L;
transient private String attribute1;
transient private String attribute2;
public myPOJO(String value1, String value2){
attribute1 = value1;
attribute2 = value2;
}
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{
//always do defaultWriteObject. Helps in few Edge cases
s.defaultWriteObject();
s.writeObject(attribute1);
s.writeObject(attribute2);
}
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException{
//always do defaultReadObject. Helps in few Edge cases.
s.defaultReadObject();
attribute1 = (String) s.readObject();
attribute2 = (String) s.readObject();
}
public String getAttribute1(){
return attribute1;
}
public void setAttribute1(String value){
attribute1 = value;
}
public String getAttribute2(){
return attribute2;
}
public void setAttribute2(String value){
attribute2 = value;
}
}