Ho creato un progetto ASP.Net WEB API che verrà utilizzato da un'applicazione mobile. Ho bisogno della risposta json per omettere le proprietà null invece di restituirle come property: null.
Come posso fare questo?
Ho creato un progetto ASP.Net WEB API che verrà utilizzato da un'applicazione mobile. Ho bisogno della risposta json per omettere le proprietà null invece di restituirle come property: null.
Come posso fare questo?
Risposte:
In WebApiConfig:
config.Formatters.JsonFormatter.SerializerSettings =
new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore};
Oppure, se desideri un maggiore controllo, puoi sostituire l'intero formattatore:
var jsonformatter = new JsonMediaTypeFormatter
{
SerializerSettings =
{
NullValueHandling = NullValueHandling.Ignore
}
};
config.Formatters.RemoveAt(0);
config.Formatters.Insert(0, jsonformatter);
config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore- questo aggiornerà la gestione del valore nullo senza resettare altre impostazioni di serializzazione json (come l'uso di lettere minuscole sulla prima lettera delle proprietà)
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)].
Per ASP.NET Core 3.0, il ConfigureServices()metodo nel Startup.cscodice dovrebbe contenere:
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.IgnoreNullValues = true;
});
Se stai usando vnext, nei progetti vnext web api, aggiungi questo codice al file 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);
});
}
Puoi anche usare [DataContract]e [DataMember(EmitDefaultValue=false)]attributi