XML 和 JSON 结果显示 WEB API 中常见 class 的不同结果

XML and JSON result showing different result for common class in WEB API

在我的 WEB API 中,我在 XML 和 Json 中得到了结果。它工作正常。但是,当我从数据库中收集数据时,一些记录是空的。在转换为 xml 或 json 时,结果不同。 输出的常见 Class 是。

public  class items
{
    [JsonProperty(PropertyName = "frequency")]
    [XmlElement(ElementName = "frequency")]
    public string Frequency { get; set; }
    [JsonProperty(PropertyName = "modulation")]
    [XmlElement(ElementName = "modulation")]
    public string Modulation { get; set; }
}

转换发生在

var Station = new items
{
    Frequency = (mContent["frequency"] is DBNull) ? null : mContent["frequency"].ToString(),
    Modulation = (mContent["modulation"] is DBNull) ? null : mContent["modulation"].ToString(),
}

对于Json结果我得到了我真正想要的:

[{"items":[{"frequency":null,"modulation":null}]}]

XML显示

<items>
  <item/>
</items>

但是我想要

 <items>
  <item>
    <frequency/>
    <modulation/>
 </item>
</items>

怎么会这样?

我想你可能想使用 XmlElementAttribute.IsNullable 属性:

public  class items
{
    [JsonProperty(PropertyName = "frequency")]
    [XmlElement(ElementName = "frequency", IsNullable = true)]
    public string Frequency { get; set; }
    [JsonProperty(PropertyName = "modulation")]
    [XmlElement(ElementName = "modulation", IsNullable = true)]
    public string Modulation { get; set; }
}

然后你应该得到:

<items>
  <item>
    <frequency xsi:nil = "true" />
    <modulation xsi:nil = "true" />
 </item>
</items>