【问题标题】:XML and JSON result showing different result for common class in WEB APIXML 和 JSON 结果显示 WEB API 中公共类的不同结果
【发布时间】:2015-09-04 11:29:47
【问题描述】:

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

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>

怎么会这样?

【问题讨论】:

  • 如果字符串 present 但为空字符串,我会期望 &lt;frequency/&gt;&lt;frequency&gt;&lt;/frequency&gt;。您目前获得的 XML 对于空引用来说似乎是完全合理的。您是否考虑过在对象初始化程序中使用 "" 而不是 null
  • 那个时候Xml结果是正确的,但是对于Json显示"frequency":"","modulation":""
  • 那是正确的,对于一个空字符串。基本上,没有与null 等价的XML ...您必须从缺少元素来推断它。 (或使用 xsi:nil - 请参阅我的答案。)

标签: c# json xml asp.net-web-api xml-serialization


【解决方案1】:

我想你可能想使用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>

【讨论】:

  • 对不起,我还有一个疑问,我得到 w3.org/2001/XMLSchema-instance" d6p1:nil="true"/> 如何删除命名空间,我是新手。这就是为什么。
  • @SanjeevS:您不应该删除命名空间。这基本上是xsi:nil,只是使用不同的别名而不是xsi可能有一种方法可以指定在任何地方使用xsi,但我不知道那会在哪里……但它不应该影响任何处理 XML 的东西。
  • 好的,感谢您的宝贵时间
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多