C
C#16mo 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
artya16mo ago
I misread your question 🤦
Chik3r
Chik3rOP16mo 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
Kouhai16mo ago
You need a custom converter
Accord
Accord16mo 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.
Want results from more Discord servers?
Add your server