Problem: Static class members are being serialized when they actually should not.
Note that I have the preview features activated which enables me to use static abstract attributes in interfaces. To have Newtonsoft ignore any fields/properties when serializing, I use a self-defined attribute taken from here:
public class JsonIgnoreSerializationAttribute : Attribute { }
class JsonPropertiesResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
{
protected override List<MemberInfo> GetSerializableMembers(Type objectType)
{
//Return properties that do NOT have the JsonIgnoreSerializationAttribute
return objectType.GetProperties()
.Where(pi => !Attribute.IsDefined(pi, typeof(JsonIgnoreSerializationAttribute)))
.ToList<MemberInfo>();
}
}
This the interface, simplified for the sake of illustration:
public interface IApiObject
{
public string ApiObjectId { get; set; }
static abstract string ObjectName { get; }
}
Now I have a class ApiObject implementing the interface:
public abstract class ApiObject : IApiObject
{
[JsonProperty(PropertyName = "api_object_id")]
[JsonIgnoreSerialization]
public string? ApiObjectId { get; set; }
[JsonIgnoreSerialization]
public static string ObjectName { get; }
}
In reality there are many more fields, but when serializing, regular members marked with this attribute are being ignored while static members are not - they are being serialized which I actually want to avoid because it causes errors on the API.
Serialization:
jsonString = JsonConvert.SerializeObject(batch, new JsonSerializerSettings { ContractResolver = new JsonPropertiesResolver() });
I wonder if this is
- a bug or
- Newtonsoft is just not supporting the preview feature
- or me not understanding/seeing something very obvious
Any suggestions?