In ASP.NET Core Web API I want to ignore null properties, when returning the following DTO class (I'm using System.Text.Json;, not Newtonsoft.Json). I want to do it in middleware (in Startup class), not in Controller. Here's the C# class:
public class VehicleOutput
{
public int VehicleId { get; set; }
public string Owner { get; set; }
public Car Car { get; set; }
public Truck Truck { get; set; }
}
This is JSON I'd like to return (I don't want to show "car": null if Car in fact is null, and same for Truck):
[
{
"vehicleId": 1,
"owner": "ABS",
"car":
{
"carId": 123,
"model": "Foo"
}
},
{
"vehicleId": 2,
"owner": "ABS",
"truck":
{
"truckId": 123,
"model": "Bar"
}
}
]
I was able to achive that by doing this in the Controller. It works!:
[HttpGet]
public async Task<ActionResult> GetVehicles()
{
var vehiclesOutput = await _vehicleService.GetVehicles();
var options = new JsonSerializerOptions
{
IgnoreNullValues = true,
WriteIndented = true
};
return Ok(JsonSerializer.Serialize(vehiclesOutput, options));
}
But I don't want to repeat this code every time I return VehicleOutput class. So I want to do it in middleware. This is what I got:
services.AddControllers()
.AddJsonOptions(opt =>
{
opt.JsonSerializerOptions.IgnoreNullValues = true;
});
It works! It ignores null properties in JSON, but it does it for every object I'm returning in the API. I want to add this option ONLY for specific classes (like VehicleOutput). How can you do that in Startup class?
Bear in mind... I'm not using Newtonsoft.Json. I'm using System.Text.Json; and I want to stick with it (if possible)