0

I searched for a while and found no answer.

I'm using the DataContractSerializer. Is it possible to make it skip the serialization of a base property?

Base class:

[KnownType(typeof(DerivedClass))]
[DataContract]
public class BaseClass
{
    [DataMember(IsRequired = false)]
    public virtual int BaseProperty{ get; set; }

    //...
    //Many other properties with [DataMember]

}

Derived class:

[DataContract]
public class DerivedClass : BaseClass
{
    // *** NO [DataMember] here***
    public override int BaseProperty
    {
        get
        {
            throw new NotSupportedException("Does not apply");          
        }
        set
        {
            throw new NotSupportedException("Does not apply");          
        }
    }
}

In this case, I see the error message:

System.Runtime.Serialization.SerializationException: 'Error in line 1 position 248...Expecting element 'BaseProperty'.
alhazen
  • 1,907
  • 3
  • 22
  • 43
  • that doesn't make much sense. if `BaseClass` needs it, why skip it. – Daniel A. White Jan 26 '18 at 20:12
  • There are a dozen of common properties in the base class and there are derived classes other than the one shown. There is a single property in the base that I'd like to skip for this particular derived class (but not the rest). – alhazen Jan 26 '18 at 20:15
  • try [ScriptIgnore] atrribute;[link](https://stackoverflow.com/questions/10169648/how-to-exclude-property-from-json-serialization) – Murat Can OĞUZHAN Jan 26 '18 at 20:15
  • *IgnoreDataMember* only works on types without *[DataContract]*. My derived class needs that. – alhazen Jan 26 '18 at 20:16
  • Is it out of the question that you override the built in serializer and serilize by hand? – gh9 Jan 26 '18 at 20:22
  • Instead of `override` try to hide base class member and use `new int BaseProperty` in the derived class – NicoE Jan 26 '18 at 20:54
  • Take the field out of base class. Make a sub-base, or whatever you want to call it, add the field to this class. Have your single class inherit from base, so it is on same level as sub-base if you visualize the inheritance as a tree, and all others inherit from sub-base. – user7396598 Jan 26 '18 at 20:59
  • Not really. `DataContractSerializer` doesn't even support the `ShouldSerialize` pattern; see [here](https://stackoverflow.com/q/11394587/3744182) for details and workarounds. Possibly adding `EmitDefaultValue = false` to the base class would meet your needs? Your best bet may be to use a [serialization surrogate](https://msdn.microsoft.com/en-us/library/ms733064.aspx) to inject an appropriate [DTO](https://en.wikipedia.org/wiki/Data_transfer_object) into your object graph during serialization. – dbc Jan 27 '18 at 19:49

0 Answers0