Wyłącz właściwości z wartością null na ASP.NET Web API

I ' ve created an ASP.Net projekt WEB API, który będzie wykorzystywany przez aplikację mobilną. Potrzebuję odpowiedzi json, aby pominąć właściwości null zamiast zwracać je jako property: null.

Jak mogę to zrobić?
Author: tanguy_k, 2013-01-23

4 answers

W WebApiConfig:

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

Lub, jeśli chcesz mieć większą kontrolę, możesz zastąpić cały formatter:

var jsonformatter = new JsonMediaTypeFormatter
{
    SerializerSettings =
    {
        NullValueHandling = NullValueHandling.Ignore
    }
};

config.Formatters.RemoveAt(0);
config.Formatters.Insert(0, jsonformatter);
 112
Author: Filip W,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-03 18:56:20

Skończyłem z tym kawałkiem kodu w starcie.plik cs using ASP. NET5 1.0.0-beta7

services.AddMvc().AddJsonOptions(options =>
{
    options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});
 23
Author: sboulema,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-16 09:44:22

Jeśli używasz vnext, w projektach vNext web api, dodaj ten kod do uruchamiania.plik cs.

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

    }
 3
Author: ilker unal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-20 07:12:38

Możesz również użyć atrybutów [DataContract] i [DataMember(EmitDefaultValue=false)]

 0
Author: goofballLogic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-26 09:30:25