Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reliably convert any object to String and then back again

Is there a reliable way to convert any object to a String and then back again to the same Object? I've seen some examples of people converting them using toString() and then passing that value into a constructor to reconstruct the object again but not all objects have a constructor like this so that method wont work for all cases. What way will?

like image 292
user596186 Avatar asked Jan 16 '12 22:01

user596186


People also ask

What is the name of the method that converts an object to a String?

stringify() method. “Stringification” is the process of converting a JavaScript object to a string.

Can you convert object to String?

We can convert Object to String in java using toString() method of Object class or String. valueOf(object) method. You can convert any object to String in java whether it is user-defined class, StringBuilder, StringBuffer or anything else.

Which interface allows to save an object and reconstruct?

The key to storing and retrieving objects in a serialized form is representing the state of objects sufficient to reconstruct the object(s). Objects to be saved in the stream may support either the Serializable or the Externalizable interface.


2 Answers

Yes, it is called serialization!

 String serializedObject = "";   // serialize the object  try {      ByteArrayOutputStream bo = new ByteArrayOutputStream();      ObjectOutputStream so = new ObjectOutputStream(bo);      so.writeObject(myObject);      so.flush();      serializedObject = bo.toString();  } catch (Exception e) {      System.out.println(e);  }   // deserialize the object  try {      byte b[] = serializedObject.getBytes();       ByteArrayInputStream bi = new ByteArrayInputStream(b);      ObjectInputStream si = new ObjectInputStream(bi);      MyObject obj = (MyObject) si.readObject();  } catch (Exception e) {      System.out.println(e);  } 
like image 183
Andrew Avatar answered Oct 03 '22 02:10

Andrew


This is the code:

try {     ByteArrayOutputStream bo = new ByteArrayOutputStream();     ObjectOutputStream so = new ObjectOutputStream(bo);     so.writeObject(stringList);     so.flush();     redisString = new String(Base64.encode(bo.toByteArray()));        }  catch (Exception e) {     e.printStackTrace(); }  try {     byte b[] = Base64.decode(redisString.getBytes());      ByteArrayInputStream bi = new ByteArrayInputStream(b);     ObjectInputStream si = new ObjectInputStream(bi);     List<String> stringList2 = (List<String>)si.readObject();     System.out.println(stringList2.get(1));           }  catch (Exception e) {     e.printStackTrace();          } 
like image 22
Ashwini Adlakha Avatar answered Oct 03 '22 03:10

Ashwini Adlakha