【问题标题】:Json.NET - convert EmptyOrWhiteSpace string property to nullJson.NET - 将 EmptyOrWhiteSpace 字符串属性转换为 null
【发布时间】:2016-05-26 11:57:00
【问题描述】:

是否可以使用 [JsonProperty] 属性将任何空字符串或填充空格的字符串转换为 null?

类似:

 public class Request
 {
     [JsonProperty(NullOrWhiteSpaceValueHandling)] 
     public string Description {get;set;}
 }

渲染时跳过空值的方式相同。 当此属性为“空”时,不设置值。

【问题讨论】:

  • 默认的string 是null。 NullValueHandling = NullValueHandling.Ignorenewtonsoft.com/json/help/html/…
  • @DavidPine 空字符串或空白字符串与null 字符串不同...
  • @RB。我知道,我试图分享如何为null 做这件事。仍在寻找空白处理。

标签: c# .net json


【解决方案1】:

您需要实现自定义JsonConverter 并将其分配给JsonProperty 属性的TrimmingConverter 属性。有一个写客户TrimmingConverter详细here的例子。一旦你实现了与此类似的东西,你应该能够设置NullValueHandling 和ItemConverterType 属性。这将确保转换器将修剪字符串,并且如果它为 null、空或空格 - 它将被序列化忽略。

public class Request
{
    [
       JsonProperty(NullValueHandling = NullValueHandling.Ignore, 
                    ItemConverterType = typeof(TrimmingConverter))
    ] 
    public string Description { get; set; }
}

这是JsonProperty的官方文档。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多