.Net Core 3.0 JsonSerializer populate existing object

前端 未结 7 967
再見小時候
再見小時候 2020-12-24 10:51

I\'m preparing a migration from ASP.NET Core 2.2 to 3.0.

As I don\'t use more advanced JSON features (but maybe one as described below), and 3.0 now comes with a buil

7条回答
  •  醉话见心
    2020-12-24 11:27

    I do not know much about this new version of the plug-in, however I found a tutorial that can be followed tutorial with some examples

    Based on him I thought of this method and I imagine that he is able to solve his problem

    //To populate an existing variable we will do so, we will create a variable with the pre existing data
    object PrevData = YourVariableData;
    
    //After this we will map the json received
    var NewObj = JsonSerializer.Parse(jsonstring);
    
    CopyValues(NewObj, PrevData)
    
    //I found a function that does what you need, you can use it
    //source: https://stackoverflow.com/questions/8702603/merging-two-objects-in-c-sharp
    public void CopyValues(T target, T source)
    {
    
        if (target == null) throw new ArgumentNullException(nameof(target));
        if (source== null) throw new ArgumentNullException(nameof(source));
    
        Type t = typeof(T);
    
        var properties = t.GetProperties(
              BindingFlags.Instance | BindingFlags.Public).Where(prop => 
                  prop.CanRead 
               && prop.CanWrite 
               && prop.GetIndexParameters().Length == 0);
    
        foreach (var prop in properties)
        {
            var value = prop.GetValue(source, null);
            prop.SetValue(target, value, null);
        }
    }
    

提交回复
热议问题