.Net Core 3.0 JsonSerializer populate existing object

前端 未结 7 919
再見小時候
再見小時候 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:54

    If you already use AutoMapper in your project or don't mind having dependency on it, you can merge objects in a following way:

    var configuration = new MapperConfiguration(cfg => cfg
        .CreateMap<Model, Model>()
        .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != default)));
    var mapper = configuration.CreateMapper();
    
    var destination = new Model {Title = "Startpage", Link = "/index"};
    var source = new Model {Head = "Latest news", Link = "/news"};
    
    mapper.Map(source, destination);
    
    class Model
    {
        public string Head { get; set; }
        public string Title { get; set; }
        public string Link { get; set; }
    }
    
    0 讨论(0)
提交回复
热议问题