.NET Core: Remove null fields from API JSON response

為{幸葍}努か 提交于 2019-12-02 20:02:47

In Startup.cs, you can attach JsonOptions to the service collection and set various configurations, including removing null values, there:

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

This can also be done per controller in case you don't want to modify the global behavior:

public IActionResult GetSomething()
{
   var myObject = GetMyObject();
   return new JsonResult(myObject, new JsonSerializerSettings() 
   { 
       NullValueHandling = NullValueHandling.Ignore 
   });
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!