与ASP.Net的Web API空值燮preSS性能

问题描述:

我已经创建了将移动应用程序中使用的ASP.Net WEB API项目。我需要的响应JSON省略空的属性,而不是返回它们作为属性:空

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: null.

我怎样才能做到这一点?

How can I do this?

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);