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