2

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: {}

Online demo.

I searched for a duplicate question and I didn't find any.

0

1 Answer 1

4

You can try customizing the serialization properties via a modifier which will analyze type and property:

var serializerOptions = new JsonSerializerOptions
{
    TypeInfoResolver = new DefaultJsonTypeInfoResolver
    {
        Modifiers =
        {
            info =>
            {
                if (info.Type == typeof(MyRecord))
                {
                    foreach (var jPropInf in info.Properties)
                    {
                        if (jPropInf.Name == nameof(MyRecord.BoolProperty) 
                            && jPropInf.PropertyType == typeof(bool))
                        {
                            jPropInf.ShouldSerialize = 
                                 (_, str) => str is bool and is false;
                        }
                    }
                }
            }
        }
    }
};

var serialized = JsonSerializer.Serialize(new MyRecord(), serializerOptions);
Console.WriteLine(serialized); // prints "{}"

Check out the Customize a JSON contract doc.

Sign up to request clarification or add additional context in comments.

3 Comments

Excellent! Thanks Guru Stron for the quick answer.
Follow up question here, with 200 bounty points for a correct answer (as soon as starting the bounty is possible).
Yep, I've tried that one too =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.