Is there a way at a global level to ignore all and only bools when returning false with System.Text.Json?
I know there's this global condition, but I still need other default values to return.
JsonSerializerOptions options = new()
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault
};
Ideally would not like to add the following to all propeties individually..
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
You can't use a custom JsonConverter for all types, because then you'll have to reinvent the wheel to serialize whole thing. You also can't use a JsonConverter<bool>
(or <bool?>
), because you have to write a value in its Write()
method.
So register a DefaultJsonTypeInfoResolver
with a custom Modifiers
action that only serializes bools when their value equals true:
JsonSerializerOptions options = new()
{
TypeInfoResolver = new DefaultJsonTypeInfoResolver
{
Modifiers =
{
jsonTypeInfo =>
{
foreach (var p in jsonTypeInfo.Properties)
{
if (p.PropertyType == typeof(bool) || p.PropertyType == typeof(bool?))
{
p.ShouldSerialize = (containingObject, propertyValue) =>
{
return propertyValue as bool? == true;
};
}
}
}
}
}
};
From MS Learn: Customize a JSON contract. Works since .NET 7.