0

Use an JsonIgnore attribute to ignore a specific property, but how to ignore a specific type when serialize use Newtonsoft.Json?

public class Foo
{
  public byte[] EncodedString { get; set; }
  public string DecodedString { get; set; }
  // ... many of above
}

How can I ignore all the byte[] properties when not using the JsonIgnore attribute?

Paddi
  • 77
  • 5

1 Answers1

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

            }); ;
        }