Serialization DataMember (name) override issue

后端 未结 2 1014
忘了有多久
忘了有多久 2021-01-17 12:37

I am using a DataContractJsonSerializer and have an issue with the DataMember Name.

I made a base class and several derived classes. I need the derived classes becau

相关标签:
2条回答
  • 2021-01-17 12:52

    I had this same issue. I was using VB.NET and I had to Shadow (or Overload) the property to get WCF to respect the DataMember property in my derived class. In C# you should be able to use the new operator.

    public class DerivedClass
    {
        [DataMember(Name = "first_method")]
        new public string FirstMethod { get; protected set; }
    }
    
    0 讨论(0)
  • 2021-01-17 12:57

    The trick is to specify EmitDefaultValue = false for the base class's virtual data member, and in its implementation in the derived class return default value so the data member is not serialized. In the derived class define another data member with the required name.

    [DataContract(Name = "baseclass", Namespace = "")]
    [KnownType(typeof(DerivedClass))]
    public class BaseClass
    {
        [DataMember(Name = "attributes", EmitDefaultValue = false)]
         public virtual SomeType Fields { get; set; }
    }
    
    [DataContract(Name = "derivedclass", Namespace = "")]
    public class DerivedClass : BaseClass
    {
        public override SomeType Fields
        {
            get { return null; }
        }
    
        [DataMember(Name = "fields")]
        public SomeType DerivedFields
        {
            get { return base.Fields; }
        }
    }
    
    0 讨论(0)
提交回复
热议问题