1

How do I serialize a Generic List into a Byte Array?

public class CustomerData
{
    public int CustomerId { get; set; }
    public string CustomerName { get; set; }
    public string CustomerState { get; set; }
    public int ProductId { get; set; }
    public int QuantityBought { get; set; }
}

List<CustomerData> customerdata = new List<CustomerData>();

I know this is how to serialize a simple string into ByteArray. Trying to learn how to conduct this for more complicate lists and enumerable.

    // Input string.
    const string input = "Test";

    // Invoke GetBytes method.
    byte[] array = Encoding.ASCII.GetBytes(input);

I saw tips on on converting objects into bytes, however I am referring to generic list class.

// Convert an object to a byte array
public static byte[] ObjectToByteArray(Object obj)
{
    BinaryFormatter bf = new BinaryFormatter();
    using (var ms = new MemoryStream())
    {
        bf.Serialize(ms, obj);
        return ms.ToArray();
    }
}
  • https://learn.microsoft.com/en-us/dotnet/standard/serialization/binary-serialization – user247702 Sep 24 '18 at 16:08
  • 1
    The options are many. You could BinaryFormatter, JSON (then serialize the string to bytes), protobuf, [Microsoft.Bond](https://github.com/Microsoft/bond), [Hyperion](https://github.com/akkadotnet/Hyperion) and so on. Too broad. – spender Sep 24 '18 at 16:10

1 Answers1

-1

You can do it like this:

void Main()
{
    List<CustomerData> customerdata = new List<CustomerData>();

    /*
    ...Your logic...
    ...Add Customers to List...
    */

    var binaryFormatter = new BinaryFormatter();
    var memoryStream = new MemoryStream();
    binaryFormatter.Serialize(memoryStream, customerdata);
    var result = memoryStream.ToArray();
}

[Serializable]
public class CustomerData
{
    public int CustomerId { get; set; }
    public string CustomerName { get; set; }
    public string CustomerState { get; set; }
    public int ProductId { get; set; }
    public int QuantityBought { get; set; }
}
Keyur Ramoliya
  • 1,900
  • 2
  • 16
  • 17