c# - Json.NET - 将 EmptyOrWhiteSpace 字符串属性转换为 null

标签 c# .net json

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

类似于:

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

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

最佳答案

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

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

这是 JsonProperty 的官方文档.

关于c# - Json.NET - 将 EmptyOrWhiteSpace 字符串属性转换为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37460204/

相关文章:

c# - .NET HttpClient - 取消 CancellationToken 不取消请求

ruby - 展平嵌套的 json 对象

c# - LINQ,Left Join,抛出异常...失败,因为物化值为 null

c# - 当字符串在资源中时,为什么 String.Format 无法转义字符?

c# - EPPlus导入文件xlsm

c# - 在不连接到数据库的情况下创建 DbContext

c# - 如何将 ScrollBar 添加到 Stackpanel

c# - Google .net API v3 类 OAuth2LeggedAuthenticator 等效项

javascript - 在 NodeJS 中解析类似 JSON 的数据

java - 更改 Swagger 生成的类名称