nop
nop

Reputation: 6359

System.Text.Json - DefaultValueHandling = DefaultValueHandling.Ignore alternative

I checked 3 years old threads here and here and they state that it's not possible to set DefaultValueHandling = DefaultValueHandling.Ignore using System.Text.Json and some people switched back to Json.NET because of that. Is there a way to do that today, 3 years later?

Json.NET way

[JsonProperty("pair", DefaultValueHandling = DefaultValueHandling.Ignore)]
public string[]? Symbols { get; set; }

Upvotes: 2

Views: 1048

Answers (1)

hawkstrider
hawkstrider

Reputation: 4341

According to the documentation you can use JsonIgnore with conditions

https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-ignore-properties?pivots=dotnet-6-0

public class Forecast
{
    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
    public DateTime Date { get; set; }

    [JsonIgnore(Condition = JsonIgnoreCondition.Never)]
    public int TemperatureC { get; set; }

    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
    public string? Summary { get; set; }
};

Upvotes: 3

Related Questions