Skip to content

SerializationMethod.Map is being ignored when concrete type is not specified. #111

@joaoportela

Description

@joaoportela

When I serialize a dictionary whose keys can have different types, my types are serialized as if the SerializationMethod.Array property was defined in the serialization context.

Example linkpad:

void Main()
{
    var context = new SerializationContext {
    SerializationMethod = SerializationMethod.Map,
        EnumSerializationMethod = EnumSerializationMethod.ByName,
        CompatibilityOptions = {
            PackerCompatibilityOptions = PackerCompatibilityOptions.None
        }
    };
    var serializer = context.GetSerializer<Dictionary<string, object>>();

    var dict = new Dictionary<string, object>();
    dict["a"] = "x";
    dict["b"] = true;
    dict["c"] = 5;
    dict["myclass"] = new MyClass() { x = 8, y = "ola" };

    byte[] body = serializer.PackSingleObject(dict);

    using (FileStream fs = File.Create(@"c:\somepath\packed.bin")) {
        fs.Write(body, 0, body.Length);
    }
    Console.WriteLine(System.Convert.ToBase64String(body));
}
// Define other methods and classes here
public enum Aux {
    AuxZero = 0,
    AuxOne = 1,
    AuxTwo = 2,
    AuxThree = 3,
}
public class MyClass {
    public int x;
    public string y;
    public Aux aux;
}

Gives me {'a': 'x', 'myclass': ['AuxZero', 8, 'ola'], 'c': 5, 'b': True} when unpacked doing python -c "import msgpack; print msgpack.unpackb(open('packed.bin', 'rb').read())".

A smaller example:

void Main()
{
    var context = new SerializationContext {
        SerializationMethod = SerializationMethod.Map,
        EnumSerializationMethod = EnumSerializationMethod.ByName,
        CompatibilityOptions = {
            PackerCompatibilityOptions = PackerCompatibilityOptions.None
        }
    };
    var serializer = context.GetSerializer<dynamic>();

    byte[] body = serializer.PackSingleObject(new MyClass() { x = 8, y = "ola" });

    using (FileStream fs = File.Create(@"C:\somepath\packed.bin")) {
        fs.Write(body, 0, body.Length);
    }
    Console.WriteLine(System.Convert.ToBase64String(body));
}
// Define other methods and classes here
public enum Aux {
    AuxZero = 0,
    AuxOne = 1,
    AuxTwo = 2,
    AuxThree = 3,
}
public class MyClass {
    public int x;
    public string y;
    public Aux aux;
}

Which gives me ['AuxZero', 8, 'ola'].

Changing var serializer = context.GetSerializer<dynamic>(); in the second example to var serializer = context.GetSerializer<MyClass>(); gives me {'y': 'ola', 'aux': 'AuxZero', 'x': 8} as expected.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugDetected as bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions