简体   繁体   English

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

[英]Json with dynamic properties - deserialize into C# object

I have the following JSON when user clicks save 当用户单击“保存”时,我有以下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 }
        ]
    }

on the MVC server side (C#), I have a ViewModel and .NET deserializes this back to my viewmodel object. 在MVC服务器端(C#),我有一个ViewModel和.NET将其反序列化回我的viewmodel对象。 in this example, This object has Id, SomeField1, SomeField2, SomeField3, SomeField4. 在此示例中,此对象具有Id,SomeField1,SomeField2,SomeField3,SomeField4。

The problem I am having is that the client only sends the fields which were actually updated, so If the user never updated SomeField3 it wont be in the json and .NET for that array object will have a null as SomeeField3 ... 我遇到的问题是客户端只发送实际更新的字段,所以如果用户从未更新SomeField3,它将不会在json中,并且该数组对象的.NET将具有null作为SomeeField3 ...

so i cant get record, update all the fields to what the viewmodel is and then call an update as it will set SomeField3 to null , which is not correct - there could be data in that field which the user just didn't touch in this case .. (in another case they may have deleted their text, which then the update would be valid.. 所以我无法获取记录,将所有字段更新为viewmodel是什么然后调用更新,因为它会将SomeField3设置为null,这是不正确的 - 该字段中可能存在用户刚才没有触及的数据case ..(在另一种情况下,他们可能已经删除了他们的文本,然后更新将是有效的..

I am not sure what is the best way to tackle this problem. 我不确定解决这个问题的最佳方法是什么。 Looking forward to your suggestions. 期待您的建议。

I suggest you to post updated string in API action, then you can get your solution as : Create dynamic property mapping function : 我建议你在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;
    }
 }

Convert your request json to dynamic object and then map dynamic object to Your static class type model, Class type model initialized from your db record or any source as per your requirement. 将您的请求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);

if you are using Newton Json for Deserializing. 如果您使用Newton Json进行反序列化。 Newton Json DeserializeObject method has an overload which takes json string and JsonSerializerSettings as parameters. Newton Json DeserializeObject方法有一个重载,它以json stringJsonSerializerSettings为参数。 JsonSerializerSettings has NullValueHandling and MissingMemberHandling properties. JsonSerializerSettings具有NullValueHandlingMissingMemberHandling属性。

  • MissingMemberHandling : Gets or sets how missing members (eg JSON contains a property that isn't a member on the object) are handled during deserialization. MissingMemberHandling :获取或设置在反序列化期间处理缺少的成员(例如JSON包含不是对象成员的属性)的方式。

  • NullValueHandling : Gets or sets how null values are handled during serialization and deserialization NullValueHandling :获取或设置序列化和反序列化期间处理null值的方式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM