0

我有一个问题,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>
4

1 回答 1

1

不要在基类[DataMember]的属性上做标记EventApiDivision

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; }
}

编辑

(IsRequired=false, EmitDefaultValue=false)或者,如果属性是,您可以使用忽略null

class ApiDivision
{
    [DataMember(IsRequired=false, EmitDefaultValue=false)]
    public new ApiTeamEvent Event { get; set; }
}
于 2012-09-30T07:27:45.107 回答