C
C#2y 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);
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
}
]
[
{
"Text": "Test"
},
{
"Text": "test 2",
"Number": 1
},
{
"Text": "test 3",
"Number": null, // Tell the serializer to only serialize this null value
}
]
4 Replies
artya
artya2y ago
I misread your question 🤦
Chik3r
Chik3rOP2y ago
Always and Never wouldnt work since I only want to write it in some conditions (Text matches x value or some other condition) WhenWritingDefault would ignore all null values and WhenWritingNull wouldnt let me write null
Kouhai
Kouhai2y ago
You need a custom converter
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?