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 *.java

C:\samples>java ToStringSample
Encoded serialized version
rO0ABXNyAAlTb21lQ2xhc3MAAAAAAAAAAQIAA0kAAWlMAAFkdAASTGphdmEvbGFuZy9Eb3VibGU7T
AABc3QAEkxqYXZhL2xhbmcvU3RyaW5nO3hwf////3NyABBqYXZhLmxhbmcuRG91YmxlgLPCSilr+w
QCAAFEAAV2YWx1ZXhyABBqYXZhLmxhbmcuTnVtYmVyhqyVHQuU4IsCAAB4cL/wAAAAAAAAdAAQQUJ
DREVGR0hJSktMTU5PUA==


Reconstituted object
SomeClass 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

Answer from OscarRyz on Stack Overflow
Top answer
1 of 13
291

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 *.java

C:\samples>java ToStringSample
Encoded serialized version
rO0ABXNyAAlTb21lQ2xhc3MAAAAAAAAAAQIAA0kAAWlMAAFkdAASTGphdmEvbGFuZy9Eb3VibGU7T
AABc3QAEkxqYXZhL2xhbmcvU3RyaW5nO3hwf////3NyABBqYXZhLmxhbmcuRG91YmxlgLPCSilr+w
QCAAFEAAV2YWx1ZXhyABBqYXZhLmxhbmcuTnVtYmVyhqyVHQuU4IsCAAB4cL/wAAAAAAAAdAAQQUJ
DREVGR0hJSktMTU5PUA==


Reconstituted object
SomeClass 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

2 of 13
12

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.

🌐
How to do in Java
howtodoinjava.com › home › serialization › serialize object to string in java
Serialize Object to String in Java
July 1, 2024 - In this quick Java tutorial, we learned to convert a Java object to string representation, first by converting the object to byte[] and then its XML/JSON representation. We also learned to serialize and deserialize the strings to/from Base64 encoded values.
Discussions

java - Reliably convert any object to String and then back again - Stack Overflow
An object may, e.g., contain references to other JVMs handling their state, and this state may be not available for you to restore. Additional problems you're going to meet will include open streams, listening sockets, and almost anything else from the outer world. ... one of the greatest mistakes a single worst feature in Java, that is, after finalization. (I do love serialization ... More on stackoverflow.com
🌐 stackoverflow.com
java - How to write serializable object to String without writing to file? - Stack Overflow
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 More on stackoverflow.com
🌐 stackoverflow.com
How to convert object to string ?
Usually toString() method can be overridden by any class to acheive this. In your case MyDate class. Overrid toString() and add your own logic and to return formatted date. More on reddit.com
🌐 r/javahelp
4
2
October 7, 2020
Explain like i'm five - what is Serializable?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
9
24
April 26, 2024
🌐
JanBask Training
janbasktraining.com › community › sql-server › how-to-serialize-an-object-into-a-string
How to serialize an object into a string | JanBask Training Community
July 5, 2021 - 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( " Reconstituted object"); System.out.println( some ); } /** Read the object from Base64 string.
🌐
Google Groups
groups.google.com › g › comp.lang.java.programmer › c › 97_ulrr34bg
Serializable java object to a string
Example: import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; import javax.xml.bind.DatatypeConverter; public class SerFun { public static String anySerialize(Object o) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(o); oos.close(); return DatatypeConverter.printBase64Binary(baos.toByteArray()); } public static Object anyD
🌐
Baeldung
baeldung.com › home › java › different serialization approaches for java
Different Serialization Approaches for Java | Baeldung
July 18, 2025 - It can parse Java structures such as String, List, and Map. The entry point for SnakeYAML is the Yaml class, which contains several methods that help in serialization and deserialization. To deserialize YAML input into Java objects, we can load a single document with the load() method and multiple documents with the loadAll() method.
🌐
Oracle
docs.oracle.com › javase › tutorial › jndi › objects › serial.html
Serializable Objects (The Java™ Tutorials > Java Naming and Directory Interface > Java Objects in the Directory)
A (Java) class can override this default serialization and define its own way of serializing objects of that class. The Object Serialization Specification describes object serialization in detail. When an object is serialized, information that identifies its class is recorded in the serialized stream. However, the class's definition ("class file") itself is not recorded. It is the responsibility of the system that is deserializing the object to determine how to locate and load the necessary class files.
🌐
Delft Stack
delftstack.com › home › howto › java › java serialize object to string
How to Serialize Object to String in Java | Delft Stack
February 2, 2024 - To serialize an object to a string, we can use the base 64 encodings. We can implement the serialization by creating two classes, one class will implement the Serializable class, and the other class will be used to create the object of the ...
Find elsewhere
🌐
Baeldung
baeldung.com › home › java › core java › introduction to java serialization
Introduction to Java Serialization | Baeldung
May 11, 2024 - This method can read a stream of bytes and convert it back into a Java object. It can then be cast back to the original object. Let’s illustrate serialization with a Person class. Note that static fields belong to a class (as opposed to an object) and are not serialized. Also, note that we can use the keyword transient to ignore class fields during serialization: public class Person implements Serializable { private static final long serialVersionUID = 1L; static String country = "ITALY"; private int age; private String name; transient int height; // getters and setters }
🌐
GeeksforGeeks
geeksforgeeks.org › java › serialization-and-deserialization-in-java
Serialization and Deserialization in Java - GeeksforGeeks
June 2, 2025 - Platform-Independent: In Java, the serialization is a platform-independent process. It means that if we serialize an object using a byte stream on one platform can be easily deserialized on different platforms. Serializable Interface: If we want to make a class serializable, then it must implement the Serializable interface.
🌐
Coderanch
coderanch.com › t › 276844 › java › Converting-Object-String
Converting Object to String (I/O and Streams forum at Coderanch)
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums · this forum made possible by our volunteer staff, including ... ... Hi folks! I have an application that needs to send a serialized object, as String, to another object.
🌐
DigitalOcean
digitalocean.com › community › tutorials › serialization-in-java
Serialization in Java - Java Serialization | DigitalOcean
August 3, 2022 - Serialization in java is implemented by ObjectInputStream and ObjectOutputStream, so all we need is a wrapper over them to either save it to file or send it over the network. Let’s see a simple Serialization in java program example. package com.journaldev.serialization; import java.io.Se...
🌐
Codementor
codementor.io › java › tutorial › serialization-and-deserialization-in-java
Serialization and Deserialization in Java | Codementor
As printed on the console below, we can observe that our serialization and deserialization methods in JAVA program were able to serialize and deserialize the data value object, respectively. We can observe that the values of the fields contractID and passKeys are null (default string value) and were declared as transient, and therefore, were not stored in the file while saving the objects’ state into the byte stream.
🌐
Tutorialspoint
tutorialspoint.com › java › java_serialization.htm
Java - Serialization
The return value is Object, so you will need to cast it to its appropriate data type. To demonstrate how serialization works in Java, I am going to use the Employee class that we discussed early on in the book. Suppose that we have the following Employee class, which implements the Serializable interface − · public class Employee implements java.io.Serializable { public String ...
🌐
Medium
medium.com › @pratik.941 › serialization-and-deserialization-in-java-6dbd11fd31b3
Serialization and Deserialization in Java | by Pratik T | Medium
July 29, 2024 - Serialization and Deserialization in Java Serialization is the process of converting an object into a byte stream, making it possible to store the object or transmit it over a network …
🌐
Great Learning
mygreatlearning.com › blog › it/software development › serialization and deserialization in java with examples
Serialization and Deserialization in Java with Examples
June 27, 2025 - The java.io.Serializable interface is the core of serialization. Your class must implement this marker interface to be serializable. A marker interface has no methods to implement. It simply tells the JVM that objects of this class can be serialized.
Top answer
1 of 2
4

This would be one way:

Copytry 
{
    // 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:

Copyprivate 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:

Copy 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;
   }
2 of 2
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)

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

convert Object to base64 JSON

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

//read base64

Copypublic 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());
}
🌐
PVS-Studio
pvs-studio.com › en › blog › posts › java › 1190
Java serialization: let′s dig it up
November 22, 2024 - As mentioned before, saving the object to the file is just one of the serialization options. Next, we instantiate the ObjectOutputStream object, which performs the actual serialization. ... public static void main(String[] args) throws ....
🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › specs › serialization › protocol.html
Java Object Serialization Specification: 6 - Object Serialization Stream Protocol
January 20, 2026 - The array of fields of the class that are serialized by the default mechanismFor arrays and object fields, the type of the field is included as a string which must be in “field descriptor” format (e.g., “Ljava/lang/Object;”) as specified in The Java Virtual Machine Specification.
🌐
Mkyong
mkyong.com › home › java › java serialization and deserialization examples
Java Serialization and Deserialization Examples - Mkyong.com
October 6, 2021 - In Java, we have to implement the Serializable interface to supports serialization and deserialization. ... package com.mkyong.io.object; import java.io.Serializable; import java.math.BigDecimal; public class Person implements Serializable { private String name; private int age; private BigDecimal salary; // getters setters constructor }