Skip to content

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

@abrasat

Description

@abrasat

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions