具有动态属性的Json - 反序列化为C#对象

时间:2017-04-03 07:15:11

标签: c# json asp.net-mvc dynamic deserialization

当用户点击保存时,我有以下JSON

tasks      : {
        updated : [
            { Id : 123, SomeField1 : 'new value', SomeField2 : 'new value', SomeField3 : 'new value' },
            { Id : 125, SomeField2 : 'new value' },
            { Id : 127, SomeField1 : 'new value', SomeField4 : 'new value' },
            { Id : 129, SomeField2 : 'new value', SomeField3 : 'new value' },
            { ................ }
        ],
        removed : [
            { Id : 345 },
            { Id : 847 }
        ]
    }
在MVC服务器端(C#)上,我有一个ViewModel,.NET将它反序列化回我的viewmodel对象。 在此示例中,此对象具有Id,SomeField1,SomeField2,SomeField3,SomeField4。

我遇到的问题是客户端只发送实际更新的字段,因此如果用户从未更新过SomeField3,那么它将不会出现在json中,并且该数组对象的.NET将具有null作为SomeeField3 ...

所以我无法获取记录,将所有字段更新为viewmodel是什么,然后调用更新,因为它将SomeField3设置为null,这是不正确的 - 该字段中可能存在用户刚刚没有的数据触摸这种情况..(在另一种情况下,他们可能已经删除了他们的文本,然后更新将是有效的..

我不确定解决这个问题的最佳方法是什么。 期待您的建议。

2 个答案:

答案 0 :(得分:0)

我建议您在API操作中发布更新的字符串,然后您可以获得以下解决方案: 创建动态属性映射功能:

    public static class DynamicToStatic
    {
     public static T ToStatic<T>(object source, T destination)
     {
        var entity = destination;

        //source implements dictionary
        var properties = source as IDictionary<string, object>;

        if (properties == null)
            return entity;

        foreach (var entry in properties)
        {
            var propertyInfo = entity.GetType().GetProperty(entry.Key);
            if (propertyInfo != null && entry.Value != null)//Check property and its values exist or not ,change only when source contains value
                propertyInfo.SetValue(entity, entry.Value, null);
        }
        return entity;
    }
 }

将您的请求json转换为动态对象,然后将动态对象映射到您的静态类类型模型,根据您的要求从您的db记录或任何源初始化的类型模型。

//updatedJsonObjectString bound from request post data(JSONSTRINGIFY of post data)
dynamic source = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(updatedJsonObjectString);
Class1 model = new Class1();//mapped/filled by data call
var retUser = DynamicToStatic.ToStatic<Class1>(source, model);

答案 1 :(得分:0)

如果您使用Newton Json进行反序列化。 Newton Json DeserializeObject方法有一个重载,它以json stringJsonSerializerSettings为参数。 JsonSerializerSettings具有NullValueHandlingMissingMemberHandling属性。

  • MissingMemberHandling :获取或设置缺少成员的方式(例如,JSON包含不是对象上的成员的属性) 在反序列化期间。

  • NullValueHandling :获取或设置序列化和反序列化期间处理空值的方式