Using JSON.net, how do I prevent serializing properties of a derived class, when used in a base class context?

后端 未结 6 1600
花落未央
花落未央 2020-12-01 00:20

Given a data model:

[DataContract]
public class Parent
{
    [DataMember]
    public IEnumerable Children { get; set; }
}

[DataContract]
publ         


        
6条回答
  •  臣服心动
    2020-12-01 00:39

    I use a custom Contract Resolver to limit which of my properties to serialize. This might point you in the right direction.

    e.g.

    /// 
    /// json.net serializes ALL properties of a class by default
    /// this class will tell json.net to only serialize properties if they MATCH 
    /// the list of valid columns passed through the querystring to criteria object
    /// 
    public class CriteriaContractResolver : DefaultContractResolver
    {
        List _properties;
    
        public CriteriaContractResolver(List properties)
        {
            _properties = properties
        }
    
        protected override IList CreateProperties(
            JsonObjectContract contract)
        {
            IList filtered = new List();
    
            foreach (JsonProperty p in base.CreateProperties(contract))
                if(_properties.Contains(p.PropertyName)) 
                    filtered.Add(p);
    
            return filtered;
        }
    }
    

    In the override IList function, you could use reflection to populate the list with only the parent properties perhaps.

    Contract resolver is applied to your json.net serializer. This example is from an asp.net mvc app.

    JsonNetResult result = new JsonNetResult();
    result.Formatting = Formatting.Indented;
    result.SerializerSettings.ContractResolver = 
        new CriteriaContractResolver(Criteria);
    

提交回复
热议问题