'MessagePack subtype serialization

Serialization/deserialization turns a collection of a base type with child-type items in it into a collection with base type items only.

Is there a way to set up the process so items would end up of the exact same type? Tried various resolvers to no avail. Also to note, that the attribute option that uses Union - [MessagePack.Union(0, typeof(Child))] is not suitable as sometimes there's no way to keep types abstract/interface.

In the following example, three objects of Child, AnotherChild types are serialized and then deserialized into three objects of the Base type.

var cache = new ItemCache
{
    Items = new List<Base>
    {
        new Child { BaseProperty = 1, ChildProperty = 0},
        new AnotherChild { BaseProperty = 2, AnotherChildProperty = 1},
        new AnotherChild { BaseProperty = 3, AnotherChildProperty = 2}
    }
};

var serializedData = MessagePackSerializer.Serialize(cache);
var deserializedData = MessagePackSerializer.Deserialize<ItemCache>(serializedData);

[MessagePackObject]
public class ItemCache
{
    [Key(0)] public List<Base> Items { get; set; }
}

[MessagePackObject]
public class Base
{
    [Key(1)] public int BaseProperty { get; set; }
}

[MessagePackObject]
public class Child : Base
{
    [Key(2)] public int ChildProperty { get; set; }
}

[MessagePackObject]
public class AnotherChild : Base
{
    [Key(2)] public int AnotherChildProperty { get; set; }
}


Solution 1:[1]

You cannot do it without union, unless you make your own resolver/formatter.

Here is one I wrote, where you don't have to use union: Polymorphic MessagePack https://github.com/Phylum123/PolymorphicMessagePack/tree/master/PolymorphicMessagePack

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jason Tower