Ignoring attributes of a generated class

Jul 30, 2009 at 5:07 PM

I have a generated class I want to be able to serialize.  But I need to exclude some of the properties.  I can't add attributes to the properties, so is there a way I can write a JsonConverter that would just skip the whole object?  Or a formatter?  Or any other way?

Jul 31, 2009 at 10:52 AM

You could inherit from DefaultContractResolver and override CreateProperties. For that type find the property you don't want to serialize and set Ignored to true.

Aug 25, 2009 at 1:06 PM

I implemented an attribute for classes and then did as James suggested, works good if anyone is interested:


[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
 public sealed class JsonIgnoreMemberAttribute : Attribute
        public JsonIgnoreMemberAttribute(string name)
            Name = name;

        /// Name of field(s) or property(s) to ignore. 
        /// Makes it easier to ignore in partial classes. 
        /// Comma separate multiple.
        public string Name { get; set; }


public partial class company {}

Custom ContactResolver:


public class IgnoreMemberContractResolver : DefaultContractResolver
    internal static readonly IContractResolver Instance = new IgnoreMemberContractResolver();

    protected override JsonProperty CreateProperty(JsonObjectContract contract, MemberInfo member)
        var val = base.CreateProperty(contract, member);
        if (!val.Ignored)
            foreach (var attribute in member.DeclaringType.GetCustomAttributes(true))
                if (attribute is JsonIgnoreMemberAttribute)
                    var names = ((JsonIgnoreMemberAttribute) attribute).Name.Split(',');
                    val.Ignored = (Array.IndexOf(names, member.Name) > -1);
        return val;





May 11, 2011 at 7:29 AM

How do I actually use the IgnoreMemberContractResolver class? This didn't work for me :( .