How To Serialize Java Object

  1. How To Serialize Java Object To File
  2. How To Serialize Java Object To Byte Array
  3. How To Serialize A Java Object
  4. How To Save A Serialized Java Object
  5. Java Serializable Example
  • Java Tutorial
  • Java Object Oriented

Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object. Jun 07, 2018  Kryo is a Java Object Serialization Framework. Because it is faster and more efficient than Java’s native serialization, it is widely used, for instance, in Spark and Flink which process the.

  • Java Advanced
  • Java Useful Resources
  • Selected Reading

Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.

After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.

Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.

The ObjectOutputStream class contains many write methods for writing various data types, but one method in particular stands out −

The above method serializes an Object and sends it to the output stream. Similarly, the ObjectInputStream class contains the following method for deserializing an object −

This method retrieves the next Object out of the stream and deserializes it. 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 −

Example

Notice that for a class to be serialized successfully, two conditions must be met −

  • The class must implement the java.io.Serializable interface.

  • All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

If you are curious to know if a Java Standard Class is serializable or not, check the documentation for the class. The test is simple: If the class implements java.io.Serializable, then it is serializable; otherwise, it's not.

Angel, Steelman, Vampire, Frankenstein, Messi and many other skins are available for your selection. Don’t panic if you are dead in Survival mode – you can always get Resurrection pack instantly in the game’s Shop and get back all of your inventory after resurrection!Customize your character by choosing unique skin from 160+ available skins for Multiplayer games. Download it now and enjoy!- Now you can ride a horse in Survival mode- Find and kill any horse to get the saddle drop- Added localization to German, Spanish, Ukrainian, French, Italian, Turkish, Spanish, Portuguese, Swedish, Russian, Japanese, Chinese and Korean- Added animals taming. Play cube world no download. What's new in this versionHUGE update with tons of new features and improvements! All skins are grouped into 7 themed skin packs: FUTURISTIC, MOSNTERS, CARTOON, SPORT and others.Select your favorite Blocks Texture Pack.

Serializing an Object

The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program instantiates an Employee object and serializes it to a file.

When the program is done executing, a file named employee.ser is created. The program does not generate any output, but study the code and try to determine what the program is doing.

Note − When serializing an object to a file, the standard convention in Java is to give the file a .ser extension.

Example

Deserializing an Object

The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo program. Study the program and try to determine its output −

Example

This will produce the following result −

Output

Here are following important points to be noted −

  • The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject() method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class. If the JVM can't find a class during the deserialization of an object, it throws a ClassNotFoundException.

  • Notice that the return value of readObject() is cast to an Employee reference.

  • The value of the SSN field was 11122333 when the object was serialized, but because the field is transient, this value was not sent to the output stream. The SSN field of the deserialized Employee object is 0.

Active2 months ago

I am able to serialize an object into a file and then restore it again as is shown in the next code snippet. I would like to serialize the object into a string and store into a database instead. Can anyone help me?

How To Serialize Java Object To File

casperOne
66.4k14 gold badges161 silver badges228 bronze badges
Sergio del AmoSergio del Amo
32.8k63 gold badges142 silver badges175 bronze badges

13 Answers

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.

Output:

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

Community
OscarRyz

How To Serialize Java Object To Byte Array

OscarRyz
148k99 gold badges350 silver badges525 bronze badges

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.

Outlaw ProgrammerOutlaw Programmer
8,3817 gold badges39 silver badges60 bronze badges

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.

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.

Sergio del AmoSergio del Amo
32.8k63 gold badges142 silver badges175 bronze badges

XStream provides a simple utility for serializing/deserializing to/from XML, and it's very quick. Storing XML CLOBs rather than binary BLOBS is going to be less fragile, not to mention more readable.

skaffmanskaffman
354k91 gold badges748 silver badges734 bronze badges
KristianKristian
3,6336 gold badges24 silver badges28 bronze badges

If you're storing an object as binary data in the database, then you really should use a BLOB datatype. The database is able to store it more efficiently, and you don't have to worry about encodings and the like. JDBC provides methods for creating and retrieving blobs in terms of streams. Use Java 6 if you can, it made some additions to the JDBC API that make dealing with blobs a whole lot easier.

If you absolutely need to store the data as a String, I would recommend XStream for XML-based storage (much easier than XMLEncoder), but alternative object representations might be just as useful (e.g. JSON). Your approach depends on why you actually need to store the object in this way.

Daniel SpiewakDaniel Spiewak
48k10 gold badges99 silver badges119 bronze badges

Java8 approach, converting Object from/to String, inspired by answer from OscarRyz. For de-/encoding, java.util.Base64 is required and used.

Markus SchulteMarkus Schulte
1,7042 gold badges28 silver badges47 bronze badges

Take a look at the java.sql.PreparedStatement class, specifically the function

Then take a look at the java.sql.ResultSet class, specifically the function

How To Serialize A Java Object

Keep in mind that if you are serializing an object into a database, and then you change the object in your code in a new version, the deserialization process can easily fail because your object's signature changed. I once made this mistake with storing a custom Preferences serialized and then making a change to the Preferences definition. Suddenly I couldn't read any of the previously serialized information.

You might be better off writing clunky per property columns in a table and composing and decomposing the object in this manner instead, to avoid this issue with object versions and deserialization. Or writing the properties into a hashmap of some sort, like a java.util.Properties object, and then serializing the properties object which is extremely unlikely to change.

JoshJosh
12.2k6 gold badges40 silver badges56 bronze badges

How To Save A Serialized Java Object

The serialised stream is just a sequence of bytes (octets). So the question is how to convert a sequence of bytes to a String, and back again. Further it needs to use a limited set of character codes if it is going to be stored in a database.

Dodge RAM Service and Repair Manuals. Every Manual available online - found by our community and shared for FREE. Workshop Manual. Dodge RAM 1993 Workshop Manual. 2009 Dodge Ram 1500 Owners Manual (543 Pages) (Free) 2009 Dodge Ram 2500 3500 Owners Manual (532 Pages) (Free) 2009 Dodge Ram 3500 Owners Manual (532 Pages). Dodge ram 1500 repair manual. Dodge Ram 1500 Owner's Manual. Also See for Dodge Ram 1500. Dodge RAM 1500 Owner's Manual 358 pages. Please see your phone owners’ manual phone book entry that you are editing. For specific instructions on how to drop the Bluetooth After you are finished editing an entry in the phone book, connection. Welcome car repair expert! You've come to the right place to get affordable quality Repair Manuals for your Dodge Ram 1500. Not an auto repair expert? That's not a problem. We've worked hard over 11 years designing a website experience that makes it easy for anyone to idenify whether parts fit their car.

The obvious solution to the problem is to change the field to a binary LOB. If you want to stick with a characer LOB, then you'll need to encode in some scheme such as base64, hex or uu.

Tom Hawtin - tackline

Java Serializable Example

Tom Hawtin - tackline
131k29 gold badges190 silver badges277 bronze badges

You can use the build in classes sun.misc.Base64Decoder and sun.misc.Base64Encoder to convert the binary data of the serialize to a string. You das not need additional classes because it are build in.

Saboteur
CiNNCiNN
7,3726 gold badges37 silver badges52 bronze badges
priyanka_raopriyanka_rao
KristianKristian
3,6336 gold badges24 silver badges28 bronze badges

Not the answer you're looking for? Browse other questions tagged javaserialization or ask your own question.