0

I was creating a simple android application in which I am converting an object to String. How can I re-convert the object from the string?

I am converting my object to String using the following line of code.

String convertedString = object.toString();
Mitesh Vanaliya
  • 2,491
  • 24
  • 39
Ali Haider
  • 374
  • 2
  • 3
  • 14

4 Answers4

0

You can't**, because that is not what the toString method is for. It's used to make a readable representation of your Object, but it's not meant for saving and later reloading.

What you are looking for instead is Serialization. See this tutorial here to get started:

http://www.tutorialspoint.com/java/java_serialization.htm

** Technically you could, but you shouldn't.

Erik
  • 3,598
  • 14
  • 29
0

You can do it in two ways:

  • Java Serialization
  • Using Gson library (more simple), remember the the purpose of this lib is to convert simply json to object and viceversa when working with REST services.

Hope it helps

appersiano
  • 2,670
  • 22
  • 42
0

You can use Serialization to convert object to string and vise versa:

 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);
 }
Mitesh Vanaliya
  • 2,491
  • 24
  • 39
0

Use Java Serialization for doing same.

Go with below link for better understand how to convert java object.
Ex. http://www.geeksforgeeks.org/serialization-in-java/

Also You can go with this link:

How to convert the following json string to java object?