Stworzyłem projekt ASP.Net WEB API, który będzie używany przez aplikację mobilną. Potrzebuję pliku JSON odpowiedzi, aby pominąć właściwości null zamiast zwracać je jako property: null.
Jak mogę to zrobić?
Stworzyłem projekt ASP.Net WEB API, który będzie używany przez aplikację mobilną. Potrzebuję pliku JSON odpowiedzi, aby pominąć właściwości null zamiast zwracać je jako property: null.
Jak mogę to zrobić?
Odpowiedzi:
W WebApiConfig:
config.Formatters.JsonFormatter.SerializerSettings =
new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore};
Lub, jeśli chcesz mieć większą kontrolę, możesz wymienić cały formater:
var jsonformatter = new JsonMediaTypeFormatter
{
SerializerSettings =
{
NullValueHandling = NullValueHandling.Ignore
}
};
config.Formatters.RemoveAt(0);
config.Formatters.Insert(0, jsonformatter);
config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore- zaktualizuje to obsługę wartości null bez resetowania innych ustawień serializacji json (np. Używanie małych liter w pierwszej literze właściwości)
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)].
W przypadku ASP.NET Core 3.0 ConfigureServices()metoda w Startup.cskodzie powinna zawierać:
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.IgnoreNullValues = true;
});
Jeśli używasz vnext, w projektach vnext Web API, dodaj ten kod do pliku startup.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);
});
}
Możesz także użyć atrybutów [DataContract]i[DataMember(EmitDefaultValue=false)]