Excluding/Including Properties Programmatically

Mar 25, 2010 at 1:48 AM

I'm using the following resolver to specify the properties I want to include for serialization:

    class CustomResolver : DefaultContractResolver
    {
        public CustomResolver()
        {
        }

        private List<string> _propertyNames = new List<string>();

        public List<string> PropertyNames
        {
            get { return _propertyNames; }
            set { _propertyNames = value; }
        }

        protected override IList<JsonProperty> CreateProperties(JsonObjectContract contract)
        {
            IList<JsonProperty> properties = base.CreateProperties(contract);

            properties = properties.Where(p => _propertyNames.Contains(p.PropertyName)).ToList();

            return properties;
        }
    }

 

This works great for an object with a single level hierarchy, but I'm looking for a way to distinguish between multiple hierarchy levels. Take the following data for example:

    class MyData
    {
        public string Prop1 { get; set; }
        public string Prop2 { get; set; }
        public string Prop3 { get; set; }
        public MyInnerData InnerData { get; set; }
    }

    class MyInnerData
    {
        public string Prop1 { get; set; }
        public string Prop2 { get; set; }
        public string Prop3 { get; set; }
    }

 

If I serialize MyData like this:

            MyData d = new MyData(); //assume this is fully populated

            JsonSerializerSettings settings = new JsonSerializerSettings();
            
            CustomResolver customResolver = new CustomResolver();
            customResolver.PropertyNames.Add("Prop1");
            customResolver.PropertyNames.Add("Prop2");
            customResolver.PropertyNames.Add("InnerData");
            settings.ContractResolver = customResolver;
            
            string json = JsonConvert.SerializeObject(d, Formatting.None, settings);

Prop3 won't be serialized on either object. But what if I want Prop3 to be serialized on the top level object and not the inner one? Ideally I would like to do something like this:

customResolver.Add("InnerData.Prop3");


Does the resolver have any context of where it is currently at in the hierarchy (or does anyone have any ideas as to how I might determine what level I'm at?) so I could determine which properties I wanted in the CreateProperties method? I can't just go add the attribute to the properties I want because it changes in each situation (plus I can't modify the objects because they are generated anyways).