Home > OS >  System.Text.Json - DefaultValueHandling = DefaultValueHandling.Ignore alternative
System.Text.Json - DefaultValueHandling = DefaultValueHandling.Ignore alternative

Time:06-18

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; }

CodePudding user response:

According to the documentation you can use JsonIgnore with conditions

https://docs.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; }
};
  • Related