2

I want to write a class object to the string and then again create an object from it. I searched on the net but all I found is to write an object to file however I want to write in the string, not on file.

Below is the example of writing to file similarly I want to write in String or similar Object and not in the file.

some_class implements serializable {
    ...
}

FileOutputStream f = new FileOutputStream(new File("myObjects.txt"));
ObjectOutputStream o = new ObjectOutputStream(f);

// Write objects to file
o.writeObject(object1);

o.close();
f.close();

FileInputStream fi = new FileInputStream(new File("myObjects.txt"));
ObjectInputStream oi = new ObjectInputStream(fi);

// Read objects
some_class object2 = (some_class) oi.readObject();

oi.close();
fi.close();

Please help with the same.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
MUKHTAR INAMDAR
  • 85
  • 4
  • 17

2 Answers2

4

This would be one way:

try 
{
    // To String
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream os = new ObjectOutputStream(bos);
    os.writeObject(object1);
    String serializedObject1 = bos.toString();
    os.close();

    // To Object 
    ByteArrayInputStream bis = new ByteArrayInputStream(serializedObject1.getBytes());
    ObjectInputStream oInputStream = new ObjectInputStream(bis);
    YourObject restoredObject1 = (YourObject) oInputStream.readObject();            

    oInputStream.close();
} catch(Exception ex) {
    ex.printStackTrace();
}

I would prefer the Base64 way though.

This would be an example of encoding:

private static String serializableToString( Serializable o ) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(o);
        oos.close();
        return Base64.getEncoder().encodeToString(baos.toByteArray()); 
    }

And this is an example of decoding:

 private static Object objectFromString(String s) throws IOException, ClassNotFoundException 
   {
        byte [] data = Base64.getDecoder().decode(s);
        ObjectInputStream ois = new ObjectInputStream( 
                                        new ByteArrayInputStream(data));
        Object o  = ois.readObject();
        ois.close();
        return o;
   }
Renis1235
  • 4,116
  • 3
  • 15
  • 27
0

the best way to serialize an object to String and vice versa you should convert the object into JSON String and encode into base64. and to get object decode base64 and convert to object using GSON (opensource google provide java library)

class foo{ String name, email;
//setter getter
}

convert Object to base64 JSON

public static String convertToJson(Object o){
       String result=new Gson().toJson(o);
       return Base64.getEncoder().encodeToString(result);
}

//read base64

public static <T> T convertJsonToObject(String base64Object,Class<T> classOfT){
    Gson gson = new Gson();
    return gson.fromJson(new InputStreamReader(new ByteArrayInputStream(Base64.getDecoder().decode(base64Object))),classOfT);
}

public static void main(String[] args) {
    foo obj=new foo("jhon","jhon@gamil.com");
    String json=convertToJson(foo);
    System.out.println(json);
    foo obj_fromJson=convertJsonToObject(json,foo.class);
    System.out.println(obj_fromJson.getName());
}