.Net Core 3.0 JsonSerializer populate existing object

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

    If its just one usage and you don't want to add extra dependencies / lots of code, you don't mind a bit of inefficiency and I've not missed something obvious, you can just use:

        private static T ParseWithTemplate(T template, string input) 
        {
            var ignoreNulls = new JsonSerializerOptions() { IgnoreNullValues = true };
            var templateJson = JsonSerializer.ToString(template, ignoreNulls);
            var combinedData = templateJson.TrimEnd('}') + "," + input.TrimStart().TrimStart('{');
            return JsonSerializer.Parse(combinedData);
        }
    

提交回复
热议问题