简体   繁体   中英

Json with dynamic properties - deserialize into C# object

I have the following JSON when user clicks save

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. in this example, This object has 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 ...

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..

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 :

    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.

//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 DeserializeObject method has an overload which takes json string and JsonSerializerSettings as parameters. JsonSerializerSettings has NullValueHandling and MissingMemberHandling properties.

  • MissingMemberHandling : Gets or sets how missing members (eg JSON contains a property that isn't a member on the object) are handled during deserialization.

  • NullValueHandling : Gets or sets how null values are handled during serialization and deserialization

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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