【问题标题】:DataContractSerialization and the new keyword inheritanceDataContractSerialization 和新的关键字继承
【发布时间】:2012-09-21 11:34:31
【问题描述】:

我有一个问题,XML 元素“事件”由于 new 关键字而被序列化两次。我希望派生类型只被序列化。

[DataContract(Name = "Division", Namespace = "")]
    public class ApiTeamDivision : ApiDivision
    {
        [DataMember]
        public new ApiTeamEvent Event { get; set; }
        [JsonIgnore]
        public new ApiDivisionSettings Settings { get; set; }
        [JsonIgnore]
        public new List<ApiPrice> Prices { get; set; }
        [JsonIgnore]
        public new List<ApiTeam> Teams { get; set; }
        [JsonIgnore]
        public new List<ApiAsset> Assets { get; set; }
        [JsonIgnore]
        public new List<ApiBracket> Brackets { get; set; }
    }   

<Division>
<Age>17</Age>
<Event i:nil="true"/>
<Event>
   <Address i:nil="true"/>
   <Assets i:nil="true"/>
   <Description i:nil="true"/>
   <Divisions i:nil="true"/>
</Event>
</Division>

【问题讨论】:

    标签: c# inheritance serialization xml-serialization datacontractserializer


    【解决方案1】:

    不要在基类ApiDivision 的属性Event 上标记[DataMember]

    class ApiDivision
    {
        //[DataMember] => don't mark this
        public new ApiTeamEvent Event { get; set; }
    }
    

    更多,如果你使用[DataContract],则不需要使用属性[JsonIgnore],因为它用于两种格式:json和Xml。

    所以,如果你想在序列化中忽略属性,就不要用属性[DataMember]标记它

    [DataContract(Name = "Division", Namespace = "")]
    public class ApiTeamDivision : ApiDivision
    {
        [DataMember]
        public new ApiTeamEvent Event { get; set; }
    
        public new ApiDivisionSettings Settings { get; set; }
    
        public new List<ApiPrice> Prices { get; set; }
    
        public new List<ApiTeam> Teams { get; set; }
    
        public new List<ApiAsset> Assets { get; set; }
    
        public new List<ApiBracket> Brackets { get; set; }
    }
    

    编辑

    如果属性为null,您也可以使用(IsRequired=false, EmitDefaultValue=false) 忽略:

    class ApiDivision
    {
        [DataMember(IsRequired=false, EmitDefaultValue=false)]
        public new ApiTeamEvent Event { get; set; }
    }
    

    【讨论】:

    • 如果我在序列化过程中使用这些属性的其他地方使用基类会怎样。
    猜你喜欢
    • 2014-02-27
    • 2015-12-04
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多