1

Is it possible to ignore a property of a parent class when serializing a child class into XML? I also want to do this with JSON if possible, but I'd like xml working first if it is doable.

For example, if I have a base class like this:

    [Serializable]
    [DataContract]
    public abstract class BaseClass
    {
        protected string _correlationID;
        private bool _isValid;

        /// <summary>
        /// get/set the correlation id
        /// </summary>
        [DataMember]
        public virtual string CorrelationID
        {
            get{ return _correlationID; }
            set{ _correlationID = value; }
        }

        /// <summary>
        /// get/set IsValid
        /// </summary>
        [DataMember]
        public virtual bool IsValid 
        {
            get { return _isValid; }
            set { _isValid = value; }
        }
    }

and a child class like this

    [Serializable]
    [DataContract]
    public class MyClass : BaseClass
    {
        private int _objectId;
        private string _objectName;

        /// <summary>
        /// get/set the object id
        /// </summary>
        [DataMember]
        public int ObjectId 
        { 
            get { return _objectId; }
            set { _objectId = value; }
        }

        /// <summary>
        /// get/set the object name
        /// </summary>
        [DataMember]
        public int ObjectName 
        { 
            get { return _objectName; }
            set { _objectName = value; }
        }

        [XmlIgnore]
        public override string CorrelationID
        {
            get{ return _correlationID; }
            set{ _correlationID = value; }
        }       
    }

I want the xml to be returned as:

<MyClass>
    <IsValid>true</IsValid>
    <ObjectId>5</ObjectId>
    <ObjectName>My Object</ObjectName>
</MyClass>

However, if I try to override the virtual property and add the xml ignore attribute to it, the xml as if I didn't specify and attribute:

<MyClass>
    <CorrelationID>12345678910</CorrelationID>
    <IsValid>true</IsValid>
    <ObjectId>5</ObjectId>
    <ObjectName>My Object</ObjectName>      
</MyClass>

I've also tried using [IgnoreDataMember], but it results in the same thing.

I am attempting to do this in MVC/Web APIs to start, but I'd like it to also be applicable to WCF if possible.

Any direction would be helpful. Thanks in advance.

4

0 回答 0