.NET Core: remove blank fields from JSON API response

Globally, in .NET Core 1.0 (all API responses), how can I configure Startup.cs so that empty fields are deleted / ignored in JSON responses?

Using Newtonsoft.Json, you can apply the following attribute to a property, but I would like not to add it to each of them:

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string FieldName { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string OtherName { get; set; } 
+5
source share
2 answers

In Startup.cs, you can attach JsonOptions to a collection of services and set various configurations, including deleting null values:

 public void ConfigureServices(IServiceCollection services) { services.AddMvc() .AddJsonOptions(options => { options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; }); } 
+9
source

This can also be done for each controller if you do not want to change the global behavior:

 public IActionResult GetSomething() { var myObject = GetMyObject(); return new JsonResult(myObject, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); }; 
0
source

Source: https://habr.com/ru/post/1268913/


All Articles