Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

Convert an Object to a Byte Array in Java

$
0
0

1. Overview

In this short tutorial, we'll learn how to convert a Java object to a byte array and vice versa.

2. Use Plain Java

For example, suppose we have a User class:

public class User implements Serializable {
    private String name;
    @Override
    public String toString() {
        return "User{name=" + name +  "}";
    }
    // getters and setters
}

We can use a ByteArrayOutputStream and ObjectOutputStream object to serializable an object to a byte array.

Let's not forget to use try-with-resources so that we don't have to worry about closing streams:

User user = new User();
user.setName("Josh");
try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
     ObjectOutputStream oos = new ObjectOutputStream(bos)) {
    oos.writeObject(user);
}

Then we'll use ByteArrayInputStream and ObjectInputStream to deserialize our received byte array to an object before finally casting it to User:

try (ByteArrayInputStream bis = new ByteArrayInputStream(data);
     ObjectInputStream ois = new ObjectInputStream(bis)) {
    User deserializedUser = (User) ois.readObject();
    System.out.println(deserializedUser);
}

Note that our User class must implement the Serializable interface. Otherwise, the above code will throw a NotSerializableException.

3. Use Apache Commons Lang

We can use the SerializationUtils class from the Apache Commons Lang library to achieve the same goal.

This class has a method named serialize(), which is used to serialize an object to a byte array:

byte[] data = SerializationUtils.serialize(user);

And a deserialize() method to deserialize byte array to object:

User deserializedUser = SerializationUtils.deserialize(data);

The above methods have parameters of type Serializable. So, our User class still needs to implement the Serializable interface, just as it did in our plain Java example.

4. Use the SerializationUtils Class of Spring Framework

Finally, if our project is already using Spring Framework, we can use the SerializationUtils class from the org.springframework.util package. The method names are the same as the ones in the Apache Commons Lang library.

First, we can serialize our User object to a byte array:

byte[] data = SerializationUtils.serialize(user);

And we can deserialize the result back to a User object:

User deserializedUser = SerializationUtils.deserialize(data);

As usual, our User class must implement the Serializable interface or we'll get a NotSerializableException when we run the above code.

5. Conclusion

In summary, we've learned three different ways to convert a Java object to a byte array and vice versa. All of these methods require the input object to implement the Serializable interface to get the job done.

       

Viewing all articles
Browse latest Browse all 4535

Trending Articles