jefffhaynes / BinarySerializer

A declarative serialization framework for controlling formatting of data at the byte and bit level using field bindings, converters, and code.
MIT License
290 stars 62 forks source link

Deserialization of byte array from network stream, with different subtypes for payload, depending on version #231

Open abrasat opened 8 months ago

abrasat commented 8 months ago

I am using the BinarySerializer to deserialize a byte array received via network from embedded devices. I need to support several versions which are not compatible. The information about the actual version is not present in the message header, so I have to set it manually using some "Version" property with the "Ignore" attribute. These are basically the classes (I did not post the detailed content of the V1_Data and V2_Data classes, as not relevant for the issue):

public class ControlDataMessage
{
    [Ignore]
    public string ControlDataVersion { get; set; }

    [FieldOrder(0)]
    public ControlHeader Header { get; set; }

    [FieldOrder(1)]
    [Subtype(nameof(ControlDataVersion), "V1", typeof(V1_ControlData))]
    [Subtype(nameof(ControlDataVersion), "V2", typeof(V2_ControlData))]
    [SubtypeDefault(typeof(EmptyControlData))]
    public ControlData Payload { get; set; }
}
public abstract class ControlData
{
}
public class V1_ControlData: ControlData
{
    public V1_Data Data { get; set; }
}
public class V2_ControlData: ControlData
{
    public V2_Data Data { get; set; }
}
public class EmptyControlData: ControlData { }

I would like to be able to use the BinarySerializer something like this:

...
var controlMsgVersion = "V1";
var _binSerializer = new BinarySerializer();
byte[] recvMsgBytes = ReceiveControlData();
var recvMsg = _binSerializer.Deserialize(recvMsgBytes, controlMsgVersion);
...

How could this be achieved?