0

Consider the following class:

public class TestClass
{
    public string Name { get; set; } = "";
    public string ValueString { get; set; } = "";

    [JsonIgnore]
    public object Value { get; set; } = "";

    [JsonIgnore]
    public List<System.Attribute> Attributes { get; } = new ();
}

When trying to serialize an instance of this object I am using the following settings:

var settings = new JsonSerializerSettings();

settings.Formatting = Formatting.Indented;
settings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
settings.DateParseHandling = DateParseHandling.DateTime;
settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
settings.DefaultValueHandling = DefaultValueHandling.Include | DefaultValueHandling.Populate;
settings.FloatFormatHandling = FloatFormatHandling.DefaultValue;
settings.FloatParseHandling = FloatParseHandling.Double;
settings.MaxDepth = null;
settings.MissingMemberHandling = MissingMemberHandling.Ignore;
settings.NullValueHandling = NullValueHandling.Include;
settings.ObjectCreationHandling = ObjectCreationHandling.Auto;
settings.PreserveReferencesHandling = PreserveReferencesHandling.All;
settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
settings.StringEscapeHandling = StringEscapeHandling.EscapeHtml;
settings.TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Full;
settings.TypeNameHandling = TypeNameHandling.All;

var json = JsonConvert.SerializeObject(this, typeof(TestClass), settings);

Exception:

JsonSerializationException: Error getting value from 'AutoGenerateField' on 'System.ComponentModel.DataAnnotations.DisplayAttribute'.
System.InvalidOperationException: The AutoGenerateField property has not been set.  Use the GetAutoGenerateField method to get the value.

This exception ONLY occurs when the Attributes property has entries even though it is marked with the [JsonIgnore] attribute.

So far I have only tried populating the list with the System.ComponentModel.DataAnnotations.DisplayAttribute class so this may happen with others.

The question is:

  1. Why is the serializer ignoring its own [JsonIgnore] attribute?
  2. What am I doing wrong, if anything, with the serializer settings (JsonSerializerSettings)?
  3. Is there another Json attribute that the Attributes property should be annotated with that I am missing?
Raheel Khan
  • 14,205
  • 13
  • 80
  • 168
  • 5
    There is also a `JsonIgnoreAttribute` in the `System.Text.Json` namespace (ie .NET built in JSON library) and they are not interchangeable. Make sure your attribute is from the correct namespace (ie `Newtonsoft.Json.JsonIgnoreAttribute`) – derpirscher Dec 11 '21 at 09:31
  • Doh! Simpson moment. Thank you. – Raheel Khan Dec 11 '21 at 10:08

0 Answers0