GroBuf icon indicating copy to clipboard operation
GroBuf copied to clipboard

Object serialization does not respect runtime types

Open Anton92nd opened this issue 4 years ago • 2 comments

GroBuf only respect primitive types, object[] and Hashtable when serializing a property of the object type, but does not respect, for example, Dictionary<TKey, TValue>.

[Test]
public void TestDictionaryInObject()
{
    var a = new A {S = "zzz", Dict = new Dictionary<string, string> {["key"] = "value"}};
    var data = serializer.Serialize(a);

    var deserializedA = serializer.Deserialize<A>(data);
    Assert.AreEqual("zzz", deserializedA.S);
    Assert.NotNull(deserializedA.Dict);
    Assert.That(deserializedA.Dict, Is.TypeOf<Dictionary<string, string>>());
    Assert.AreEqual("value", ((Dictionary<string, string>)deserializedA.Dict)["key"]);
}

public class A
{
    public object S { get; set; }
    public object Dict { get; set; }
}

This test fails on Assert.NotNull operation.

Anton92nd avatar Apr 20 '20 06:04 Anton92nd

It seems to me that it may be hard to fix because GroBuf serialization considers types known at compile-time, but it has no mechanism to call a Writer for a runtime type.

Anton92nd avatar Apr 20 '20 07:04 Anton92nd

This failing test proves that the problem is in serialization process.

        [Test]
        public void TestDictionaryInObjectSize()
        {
            var first = new A {S = "zzz", Z = new Dictionary<string, string> {["key"] = "value"}};
            var firstBytes = serializer.Serialize(first);
            
            var second = new A {S = "zzz", Z = null};
            var secondBytes = serializer.Serialize(second);
            
            Assert.AreNotEqual(firstBytes.Length, secondBytes.Length);
        }

Anton92nd avatar Apr 20 '20 07:04 Anton92nd