public class Foo
{
[JsonIgnore]
public byte[] EncodedString { get; set; }
public string DecodedString { get; set; }
}
You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options:
Always - The property is always ignored. If no Condition is specified, this option is assumed.
Never - The property is always serialized and deserialized, regardless of the DefaultIgnoreCondition, IgnoreReadOnlyProperties, and IgnoreReadOnlyFields global settings.
WhenWritingDefault - The property is ignored on serialization if it's a reference type null, a nullable value type null, or a value type default.
WhenWritingNull - The property is ignored on serialization if it's a reference type null, or a nullable value type null.
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; }
};
To prevent serialization of default values in value type properties, set the DefaultIgnoreCondition property to WhenWritingDefault, as shown in the following example:
in progam.cs dot net 6:
builder.Services.AddControllers().AddJsonOptions(p =>
{
p.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});
or dot net 5 startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews().AddJsonOptions(p =>
{
p.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
}); ;
}