Suppress properties with null value on ASP.NET Web API

前端 未结 5 1959
清歌不尽
清歌不尽 2020-11-28 05:18

I\'ve created an ASP.Net WEB API Project that will be used by a mobile application. I need the response json to omit null properties instead of return them as property

相关标签:
5条回答
  • 2020-11-28 05:31

    If you are using vnext, in vnext web api projects, add this code to startup.cs file.

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().Configure<MvcOptions>(options =>
            {
                int position = options.OutputFormatters.FindIndex(f =>  f.Instance is JsonOutputFormatter);
    
                var settings = new JsonSerializerSettings()
                {
                    NullValueHandling = NullValueHandling.Ignore
                };
    
                var formatter = new JsonOutputFormatter();
                formatter.SerializerSettings = settings;
    
                options.OutputFormatters.Insert(position, formatter);
            });
    
        }
    
    0 讨论(0)
  • 2020-11-28 05:37

    For ASP.NET Core 3.0, the ConfigureServices() method in Startup.cs code should contain:

    services.AddControllers()
        .AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.IgnoreNullValues = true;
        });
    
    0 讨论(0)
  • 2020-11-28 05:45

    You can also use [DataContract] and [DataMember(EmitDefaultValue=false)] attributes

    0 讨论(0)
  • 2020-11-28 05:50

    In the WebApiConfig:

    config.Formatters.JsonFormatter.SerializerSettings = 
                     new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore};
    

    Or, if you want more control, you can replace entire formatter:

    var jsonformatter = new JsonMediaTypeFormatter
    {
        SerializerSettings =
        {
            NullValueHandling = NullValueHandling.Ignore
        }
    };
    
    config.Formatters.RemoveAt(0);
    config.Formatters.Insert(0, jsonformatter);
    
    0 讨论(0)
  • 2020-11-28 05:54

    I ended up with this piece of code in the startup.cs file using ASP.NET5 1.0.0-beta7

    services.AddMvc().AddJsonOptions(options =>
    {
        options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
    });
    
    0 讨论(0)
提交回复
热议问题