Json.Net DeserializeObject failing with OData.Delta - integers only

前端 未结 2 1038
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-31 19:25

This problem is affecting my ASP.Net WebApi Patch method which looks a lot like this:

public MyModel Patch(int id, [FromBody]Delta newRecord){         


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-31 20:16

    This is my implementation for this issue based on Rob solution:

    public sealed class Patchable : DynamicObject where T : class {
        private readonly IDictionary changedProperties = new Dictionary();
        public override bool TrySetMember(SetMemberBinder binder, object value) {
            var pro = typeof (T).GetProperty(binder.Name);
            if (pro != null)
                changedProperties.Add(pro, value);
            return base.TrySetMember(binder, value);
        }
        public void Patch(T delta) {
            foreach (var t in changedProperties)
                t.Key.SetValue(
                    delta,
                    t.Key.PropertyType.IsEnum ? Enum.Parse(t.Key.PropertyType, t.Value.ToString()) : Convert.ChangeType(t.Value, t.Key.PropertyType));
        }
    }
    

    I removed the requisite of an empty constructor in generic type parameter using the dictionary instead of a temporal object.

    Thanks Rob ;)

提交回复
热议问题