1

I'm looking for a way in Azure Functions v4 with .NET 6 to remove null fields from the response JSON. None of the options described in this answer worked for me.

I would like these fields be omitted, currently just using return new OkObjectResult(result); (result being a list of objects)

enter image description here

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
silent
  • 14,494
  • 4
  • 46
  • 86
  • You can use the `JsonSerializerOptions` to achieve this - try this: `JsonSerializerOptions options = new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }` – marc_s Jul 10 '22 at 18:54
  • where exactly should I use that @marc_s? – silent Jul 10 '22 at 19:30

1 Answers1

0

You can achieve the desired result something like this (replacing the current return you have):

return new JsonResult(myObject, new JsonSerializerOptions() 
                                    { 
                                        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
                                    });
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • thanks! Looks like I need to use Newtonsoft JSON for this, right? Or is there a way to do this using System.Text.Json? – silent Jul 10 '22 at 19:37
  • `JsonSerializerOptions` **is** from `System.Text.Json` ..... – marc_s Jul 10 '22 at 19:43
  • strange, according to the docs it should work, but I'm getting `Argument 2: cannot convert from 'System.Text.Json.JsonSerializerOptions' to 'Newtonsoft.Json.JsonSerializerSettings'` – silent Jul 10 '22 at 19:44