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:
- Why is the serializer ignoring its own
[JsonIgnore]
attribute? - What am I doing wrong, if anything, with the serializer settings (
JsonSerializerSettings
)? - Is there another
Json
attribute that theAttributes
property should be annotated with that I am missing?