I have a record with a bool property that has default value = true:
private record MyRecord()
{
public bool BoolProperty { get; init; } = true;
}
I want to ignore the "BoolProperty":true in the serialized JSON string. In other words if the BoolProperty is true, I want this property to be omitted from the resulting JSON representation. Is this possible?
Here is a demonstration of the desirable behavior:
JsonSerializerOptions options = new();
options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault;
MyRecord obj = new();
Console.WriteLine($"Object: {obj}"); // OK
string json = JsonSerializer.Serialize(obj, options);
Console.WriteLine($"JSON: {json}"); // Not OK
The output is:
Object: MyRecord { BoolProperty = True }
JSON: {"BoolProperty":true}
The desirable output should be:
Object: MyRecord { BoolProperty = True }
JSON: {}
I searched for a duplicate question and I didn't find any.