Over a million developers have joined DZone.
Platinum Partner

Convert Object To Byte Array And Viceversa (serialization)

· Big Data Zone

The Big Data Zone is presented by Exaptive.  Learn about how to rapidly iterate data applications, while reusing existing code and leveraging open source technologies.



// Convert an object to a byte array
private byte[] ObjectToByteArray(Object obj)
{
    if(obj == null)
        return null;
    BinaryFormatter bf = new BinaryFormatter();
    MemoryStream ms = new MemoryStream();
    bf.Serialize(ms, obj);
    return ms.ToArray();
}
// Convert a byte array to an Object
private Object ByteArrayToObject(byte[] arrBytes)
{
    MemoryStream memStream = new MemoryStream();
    BinaryFormatter binForm = new BinaryFormatter();
    memStream.Write(arrBytes, 0, arrBytes.Length);
    memStream.Seek(0, SeekOrigin.Begin);
    Object obj = (Object) binForm.Deserialize(memStream);
    return obj;
}

p.s. for custom classes add [Serializable] attribute to enable serialization 


The Big Data Zone is presented by Exaptive.  Learn how rapid data application development can address the data science shortage.

Topics:
big data

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}