How to serialize an object into a string How to serialize an object into a string java java

How to serialize an object into a string


Sergio:

You should use BLOB. It is pretty straighforward with JDBC.

The problem with the second code you posted is the encoding. You should additionally encode the bytes to make sure none of them fails.

If you still want to write it down into a String you can encode the bytes using java.util.Base64.

Still you should use CLOB as data type because you don't know how long the serialized data is going to be.

Here is a sample of how to use it.

import java.util.*;import java.io.*;/**  * Usage sample serializing SomeClass instance  */public class ToStringSample {    public static void main( String [] args )  throws IOException,                                                      ClassNotFoundException {        String string = toString( new SomeClass() );        System.out.println(" Encoded serialized version " );        System.out.println( string );        SomeClass some = ( SomeClass ) fromString( string );        System.out.println( "\n\nReconstituted object");        System.out.println( some );    }    /** Read the object from Base64 string. */   private static Object fromString( 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;   }    /** Write the object to a Base64 string. */    private static String toString( Serializable o ) throws IOException {        ByteArrayOutputStream baos = new ByteArrayOutputStream();        ObjectOutputStream oos = new ObjectOutputStream( baos );        oos.writeObject( o );        oos.close();        return Base64.getEncoder().encodeToString(baos.toByteArray());     }}/** Test subject. A very simple class. */ class SomeClass implements Serializable {    private final static long serialVersionUID = 1; // See Nick's comment below    int i    = Integer.MAX_VALUE;    String s = "ABCDEFGHIJKLMNOP";    Double d = new Double( -1.0 );    public String toString(){        return  "SomeClass instance says: Don't worry, "               + "I'm healthy. Look, my data is i = " + i                + ", s = " + s + ", d = " + d;    }}

Output:

C:\samples>javac *.javaC:\samples>java ToStringSampleEncoded serialized versionrO0ABXNyAAlTb21lQ2xhc3MAAAAAAAAAAQIAA0kAAWlMAAFkdAASTGphdmEvbGFuZy9Eb3VibGU7TAABc3QAEkxqYXZhL2xhbmcvU3RyaW5nO3hwf////3NyABBqYXZhLmxhbmcuRG91YmxlgLPCSilr+wQCAAFEAAV2YWx1ZXhyABBqYXZhLmxhbmcuTnVtYmVyhqyVHQuU4IsCAAB4cL/wAAAAAAAAdAAQQUJDREVGR0hJSktMTU5PUA==Reconstituted objectSomeClass instance says: Don't worry, I'm healthy. Look, my data is i = 2147483647, s = ABCDEFGHIJKLMNOP, d = -1.0

NOTE: for Java 7 and earlier you can see the original answer here


How about writing the data to a ByteArrayOutputStream instead of a FileOutputStream?

Otherwise, you could serialize the object using XMLEncoder, persist the XML, then deserialize via XMLDecoder.


Thanks for great and quick replies. I will gives some up votes inmediately to acknowledge your help. I have coded the best solution in my opinion based on your answers.

LinkedList<Patch> patches1 = diff.patch_make(text2, text1);try {    ByteArrayOutputStream bos = new ByteArrayOutputStream();    ObjectOutputStream os = new ObjectOutputStream(bos);    os.writeObject(patches1);    String serialized_patches1 = bos.toString();    os.close();    ByteArrayInputStream bis = new ByteArrayInputStream(serialized_patches1.getBytes());    ObjectInputStream oInputStream = new ObjectInputStream(bis);    LinkedList<Patch> restored_patches1 = (LinkedList<Patch>) oInputStream.readObject();                    // patches1 equals restored_patches1    oInputStream.close();} catch(Exception ex) {    ex.printStackTrace();}

Note i did not considered using JSON because is less efficient.

Note: I will considered your advice about not storing serialized object as strings in the database but byte[] instead.