我在C#webservice项目中遇到了一个可以为空的属性问题。
public class Header
{
[DataMember]
public long Id { get; set; }
[DataMember]
public long SportId { get; set; }
[DataMember]
public long TournamentId { get; set; }
[DataMember]
public string TournamentName { get; set; }
[DataMember]
public string TournamentShortName { get; set; }
[DataMember]
public long StatusId { get; set; }
[DataMember]
public string StatusName { get; set; }
[DataMember]
public string StatusShortName { get; set; }
[DataMember]
public DateTime MatchDate { get; set; }
[DataMember]
public string MatchTime { get; set; }
[DataMember]
public DateTime? PeriodStartDate { get; set; }
[DataMember]
public int? Quarter1HomeTeamScore { get; set; }
[DataMember]
public int? Quarter1AwayTeamScore { get; set; }
[DataMember]
public int Quarter2HomeTeamScore { get; set; }
[DataMember]
public int Quarter2AwayTeamScore { get; set; }
[DataMember]
public int Quarter3HomeTeamScore { get; set; }
[DataMember]
public int Quarter3AwayTeamScore { get; set; }
[DataMember]
public int Quarter4HomeTeamScore { get; set; }
[DataMember]
public int Quarter4AwayTeamScore { get; set; }
}
这是序列化后的soap xml:
<LiveMatchList>
<Items>
<ListMatch>
<Header>
<Quarter1HomeTeamScore xsi:nil="true"/>
<Quarter1AwayTeamScore xsi:nil="true"/>
<Quarter2HomeTeamScore xsi:nil="true"/>
<Quarter2AwayTeamScore xsi:nil="true"/>
<Quarter3HomeTeamScore xsi:nil="true"/>
<Quarter3AwayTeamScore xsi:nil="true"/>
<Quarter4HomeTeamScore xsi:nil="true"/>
<Quarter4AwayTeamScore xsi:nil="true"/>
<Id>138906</Id>
<SportId>2</SportId>
<TournamentId>8</TournamentId>
<TournamentName> Eurocup</TournamentName>
<TournamentShortName> AVK</TournamentShortName>
<StatusId>12</StatusId>
<StatusName> 1. Periyot</StatusName>
<StatusShortName> 1.P</StatusShortName>
<MatchDate>2013-03-20T00:00:00</MatchDate>
<MatchTime> 21:30</MatchTime>
<PeriodStartDate xsi:nil="true"/>
</Header>
</ListMatch>
我尝试在http://www.xmlgrid.net/中查看xml但由于xsi:nil = "true"
节点无法查看它。在另一个使用此Web服务的项目中,我在反序列化为对象时出现错误的xml格式错误。
如何忽略null属性?或者还有另一种解决这个问题的方法吗?
我试过了:
[DataMember(EmitDefaultValue = false)]
public int? Quarter1HomeTeamScore { get; set; }
和
[DataMember(EmitDefaultValue = false)]
public int Quarter1HomeTeamScore = 0
答案 0 :(得分:1)
像这样添加EmitDefaultValue属性:
[DataMember(EmitDefaultValue = false)]
<强>更新强>
尝试 IsRequired 属性,如
[DataMember(IsRequired = false)]
正如你评论它不适合你,请查看
How to remove null DataMember properties from the response in wcf