fastBinaryJSON icon indicating copy to clipboard operation
fastBinaryJSON copied to clipboard

InvalidCastException on deserializing a property of a type that is already supported when a custom serializer is registered.

Open rbeurskens opened this issue 8 years ago • 0 comments

InvalidCastException is thrown when deserializing a property of a type that is already supported with a registered custom serializer (BJSON.RegisterCustomType(Type)).

Example test: (When I implemented build-in support for the DateTimeOffset type the same way explicit support for TimeSpan was added in v1.4.20, running the existing datetimeoff() unit test resulted in the same exception. I am not sure if it is coincidence that both are value types. )

    public class Dto
    {
        public TimeSpan date;
    }

    [Test]
    public static void MyTest()
    {
        BJSON.RegisterCustomType(typeof(TimeSpan),
            (x) => { return x.ToString(); },
            (x) => { return TimeSpan.Parse(x); }
        );
        // ^^ removing the above statement will make it work, but prevents 'overriding' the default serializer for this type (TimeSpan in this case) with a custom one (which I think is the expected behavior)
        var dt = new TimeSpan(2, 2, 2, 2);

        var t = new Dto { date = dt };

        var s = BJSON.ToBJSON(t);
        var d = BJSON.ToObject(s); // <= InvalidCastException "Unable to cast object of type 'System.TimeSpan' to type 'System.String'."
// at fastBinaryJSON.Deserializer.ParseDictionary(Dictionary`2 d, Dictionary`2 globaltypes, Type type, Object input)
// , line 535 ( oset = Reflection.Instance.CreateCustom((string)v, pi.pt); )

       // (Code below does not suffer from this issue)
        s = BJSON.ToBJSON(dt);
        d = BJSON.ToObject<TimeSpan>(s);

    }

rbeurskens avatar Aug 18 '17 09:08 rbeurskens