vader
vader

Reputation: 45

How to deserialize bytes back to my class object?

I am serializing my class to bytes and then I want to extract everything out of it while deserializing it. My class looks like this:

public class DataWork {
    private final String clientId;
    private final String serverId;

    public DataWork(final String clientId, final String serverId) {
        this.clientId = clientId;
        this.serverId = serverId;
    }

    public String getClientId() {
        return clientId;
    }

    public String getServerId() {
        return serverId;
    }

    @Override
    public String toString() {
        return "DataWork [clientId=" + clientId + ", serverId=" + serverId + "]";
    }
}

And below is my serializer class where I am serializing my DataWork to bytes but I don't know how to extract everything out of it while deserializing it back? In general I want to get full DataWork object while deserializing it using the same bytes.

public class DataSerializer implements QueueSerializer<DataWork> {

    // here I need to deserialize
    public DataWork deserialize(byte[] buffer) {
        // don't know what should I do here?
        // buffer will have my actual bytes of DataWork
    }

    // here I am serializing
    public byte[] serialize(DataWork work) {
        return work.toString().getBytes();
    }
}

Now that means I need to serialize it in such a way so that I can extract everything out of it properly while deserializing.

Upvotes: 1

Views: 261

Answers (1)

Ankur Shanbhag
Ankur Shanbhag

Reputation: 7804

Look at your toString() method implementation. It will return you bytes in same fashion.

// here I need to deserialize
    public DataWork deserialize(byte[] buffer) {

       if(null == buffer || buffer.length == 0)
             return null;

       // reconstruct the string back from bytes.
       String data = new String(buffer);

       // now just parse the string and create a new object of type DataWork 
       // with clientID and serverID field values retrieved from the string.
       String splitData = data.split(",");

       String clientID = splitData[0].split("=")[1];
       String serverID = splitData[1].split("=")[1];    

       return new DataWork(clientID, serverID.substring(0, serverID.length() -1));
    }

Note: It is better to serialize the data with minimum delimiters or else parsing would become cumbersome as in your case. Also, it will minimize the space required storage or transfer.

Upvotes: 1

Related Questions