I have an interface with a property like this:
public interface IFoo {
// ...
[JsonIgnore]
string SecretProperty { get; }
// ...
}
<
In more recent versions of Json.NET, applying [JsonIgnore] to interface properties now just works and successfully prevents them from being serialized for all implementing types, as long as the property is declared on the same class where the interface is declared. A custom contract resolver is no longer required.
For instance, if we define the following types:
public interface IFoo
{
[JsonIgnore]
string SecretProperty { get; set; }
string Include { get; set; }
}
public class Foo : IFoo
{
public string SecretProperty { get; set; }
public string Include { get; set; }
}
Then the following test passes in Json.NET 11 and 12 (and probably earlier versions also):
var root = new Foo
{
SecretProperty = "Ignore Me",
Include = "Include Me",
};
var json = JsonConvert.SerializeObject(root);
Assert.IsTrue(json == "{\"Include\":\"Include Me\"}");// Passes
Demo fiddles here and here.
I believe this was added in Json.NET 4.0.3 despite the fact that JsonIgnore
was not mentioned explicitly in the release notes:
New feature - JsonObject and JsonProperty attributes can now be placed on an interface and used when serializing implementing objects.
(The implementation can be found in JsonTypeReflector.GetAttribute
However, as noted by Vitaly, this does not work when the property is inherited from a base class of the class where the interface is declared. Demo fiddle here.