1
Vote

"System.InvalidCastException : Specified cast is not valid" while using custom IValueProvider

description

Hi.

I'm trying to convert values during object serialization using custom ValueProvider.
All works fine except TimeSpan properties. The following test throws System.InvalidCastException:

NOTE: i don't want use JsonConverters cause I have my own converters structure, which I try to use in my IValueProvider
    public class MyType {
        public TimeSpan TimeSpanProperty { get; set; }
    }
    public class DataServiceContractResolver : DefaultContractResolver {
        protected override IValueProvider CreateMemberValueProvider(MemberInfo member) {
            return new ResourceValueProvider(member);
        }
        public class ResourceValueProvider : IValueProvider {
            MemberInfo member;
            public ResourceValueProvider(MemberInfo member) {
                this.member = member;
            }
            public object GetValue(object target) {
                return ((TimeSpan)((dynamic)target).TimeSpanProperty).TotalSeconds;
            }
            public void SetValue(object target, object value) {
            }
        }
    }
    [Test]
    public void Test() {
        MyType obj = new MyType();
        obj.TimeSpanProperty = new TimeSpan(10, 0, 0);
        JsonConvert.SerializeObject(obj, new JsonSerializerSettings {
            ContractResolver = new DataServiceContractResolver(),
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
        });
    }
Please suggest or fix.

Thanks,
Vladimir

comments