Skip to content

Hide JSON properties in the result set if not set or null, using .net core 3.1 and Newtonsoft

Need to hide properties in your JSON result for a .net core API. Add the following line in your Startup.cs file. Just like below.

opts.SerializerSettings.NullValueHandling = NullValueHandling.Ignore

services.AddMvc(options =>
                {
                    options.InputFormatters.RemoveType<Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter>();
		    options.OutputFormatters.RemoveType<Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter>();
                })
                .AddNewtonsoftJson(opts =>
               {
                    opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                    opts.SerializerSettings.Converters.Add(new StringEnumConverter(new CamelCaseNamingStrategy()));
                    opts.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                })
                .AddXmlSerializerFormatters();

Published in.NetC#Coding

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *