1

Is it possible on System.Text.Json to conditionally ignore when default if it is a certain type?

Because I have this type

public struct Optional<T>
{
    public bool HasValue { get; init; } 
    public T Value { get; init; } 

    public Optional(T value) =>
        (HasValue, Value)  = (true, value);
} 

I can ignore it when default globally with JsonSerializerOptions.DefaultIgnoreCondition but this also means if I have a bool with false value or int with 0 value it will be ignored, and I only want to ignore when default if the type is specifically Optional<T>

Any suggestions?

Also, I don't want to use [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)], I know I can do that but I want to make it globally with that certain type

Cappuccino
  • 151
  • 3
  • 7
  • I can't think of any way to do it in .NET 5 other than a global converter factory for the type(s) containing `Optional` properties such as the one from [this answer](https://stackoverflow.com/a/63431434/3744182) to [Custom JSON serializer for optional property with System.Text.Json](https://stackoverflow.com/q/63418549/3744182). – dbc Sep 16 '21 at 22:38
  • In .NET 6 Microsoft is apparently exposing their metadata to application developers via [`JsonTypeInfo`](https://learn.microsoft.com/en-us/dotnet/api/system.text.json.serialization.metadata.jsontypeinfo?view=net-6.0). This looks to correspond to Json.NET's `JsonContract` type so programmatically adding `JsonSerializerOptions.DefaultIgnoreCondition` to all `Optional` properties in runtime might become much easier in .NET 6. – dbc Sep 16 '21 at 22:39
  • I think it should work, I will try and hope it works, thank you very much for the help. – Cappuccino Sep 17 '21 at 01:46
  • How about the JsonIgnoreCondition.WhenWritingNull – Wouter Jul 07 '22 at 06:55

0 Answers0