C#C
C#3y ago
Chik3r

❔ How to serialize certain null values with System.Text.Json

In System.Text.Json, if I have something like
record Item(string Text, int? Number);

List<Item> items = new();
JsonSerializerOptions options = new() {
    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault,
};
string json = JsonSerializer.Serialize(items, options);

I can serialize a list of items but ignore null values when writing, but what should I do if I want to serialize a single null value and ignore all others, something like this:
[
{
  "Text": "Test"
},
{
  "Text": "test 2",
  "Number": 1
},
{
  "Text": "test 3",
  "Number": null, // Tell the serializer to only serialize this null value
}
]
Was this page helpful?