I'm developing an ASP.NET Core web API, without EntityFrameworkCore, that uses controller classes for implementing the HTTP actions, and that generally follows this pattern:
public class MyItem
{
public string Prop1 { get; set; }
public MyOtherItem? OtherItem { get; set; }
}
public IEnumerable<MyItem> GetMyItems()
{
List<MyItem> myItems = new();
// Fill in myItems with stuff where OtherItem is sometimes null
return myItems;
}
public class MyController : ControllerBase
{
[HttpPost]
public Task<IEnumerable<MyItem>> FetchMyItems()
{
var myItems = GetMyItems();
return Task.FromResult(myItems);
}
}
On making the POST request to FetchMyItems in Postman, the response is a JSON string containing an array of MyItem objects like this:
[
{
"prop1": "a string",
"otherItem": {
"otherprop1": "a string",
"otherprop2": 0
}
},
{
"prop1": "a string",
"otherItem": null
}
]
What I would like is for the OtherItem property to be excluded if it is null. I have looked at adding the [JsonProperty(NullValueHandling=NullValueHandling.Ignore)] attribute to the class but that has no effect, probably because whatever process is happening in FromResult() is not using the JsonSerializer.
Is there a different property attribute I can use? Or do I have to alter my action to use JsonSerializer?