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?
stringify() method. “Stringification” is the process of converting a JavaScript object to a 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.
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.
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); }
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With