【问题标题】:Converting JSON to XML using JSON.NET: convert an element to an attribute only if not null使用 JSON.NET 将 JSON 转换为 XML:仅当元素不为空时才将元素转换为属性
【发布时间】:2015-05-07 17:05:06
【问题描述】:

我们使用 JSON.NET 将分层对象转换为 JSON,然后从那里转换为 XML。

我们知道反对这样做的论据,但有几个 支持它的论据,我们已经尝试了很多方法来实现它。

我们遇到的一个问题是属性偶尔会有一个空值。当property is getting converted to an element 时,这很好,但是当它是一个属性时,我们会抛出一个NullReferenceException。我们的偏好是将空值转换为空字符串,但完全不考虑它们是可以接受的。

我们该如何处理?

【问题讨论】:

  • 您从哪里获得 NRE?
  • 见下文;它在string 属性上。稍微改变一下吸气剂,就可以为这种情况提供一个坚固但针对具体情况的补丁。

标签: c# xml json json.net


【解决方案1】:

一点点分析发现,我们得到的所有NullReferenceExceptions 都在string 属性上。如果确实没有初始化字符串,我将以下内容放在 getter 中以返回 string.Empty 而不是 null这不是一个优雅的解决方案,但它适用于我们的情况。

    [JsonProperty(PropertyName = "@Code")]
    public string ProductCode
    {
        get { return _productCode == null ? string.Empty : _productCode ; }
        set { _productCode = value.Trim(); }
    }

【讨论】:

    猜你喜欢
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    相关资源
    最近更新 更多