Suppress properties with null value on ASP.NET Web API

前端 未结 5 1995
清歌不尽
清歌不尽 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: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);
    

提交回复
热议问题