How to convert an object to a byte array in C#

Viewed 241961

I have a collection of objects that I need to write to a binary file.

I need the bytes in the file to be compact, so I can't use BinaryFormatter. BinaryFormatter throws in all sorts of info for deserialization needs.

If I try

byte[] myBytes = (byte[]) myObject 

I get a runtime exception.

I need this to be fast so I'd rather not be copying arrays of bytes around. I'd just like the cast byte[] myBytes = (byte[]) myObject to work!

OK just to be clear, I cannot have any metadata in the output file. Just the object bytes. Packed object-to-object. Based on answers received, it looks like I'll be writing low-level Buffer.BlockCopy code. Perhaps using unsafe code.

14 Answers

Use of binary formatter is now considered unsafe. see --> Docs Microsoft

Just use System.Text.Json:

To serialize to bytes:

JsonSerializer.SerializeToUtf8Bytes(obj);

To deserialize to your type:

JsonSerializer.Deserialize(byteArray);

I found Best Way this method worked correcly for me Use Newtonsoft.Json

public TData ByteToObj<TData>(byte[] arr){
                    return JsonConvert.DeserializeObject<TData>(Encoding.UTF8.GetString(arr));
    }

public byte[] ObjToByte<TData>(TData data){
            var json = JsonConvert.SerializeObject(data);
            return Encoding.UTF8.GetBytes(json);
}

This method returns an array of bytes from an object.

private byte[] ConvertBody(object model)
        {
            return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(model));
        }

You can use below method to convert list of objects into byte array using System.Text.Json serialization.

private static byte[] CovertToByteArray(List<object> mergedResponse)
{
var options = new JsonSerializerOptions
{
 PropertyNameCaseInsensitive = true,
};
if (mergedResponse != null && mergedResponse.Any())
{
return JsonSerializer.SerializeToUtf8Bytes(mergedResponse, options);
}

 return new byte[] { };
}
Related