是否可以使用 [JsonProperty] 属性将任何空字符串或用空格填充的字符串转换为 null?
类似于:
public class Request
{
[JsonProperty(NullOrWhiteSpaceValueHandling)]
public string Description {get;set;}
}
与渲染时跳过 null 的方式相同。 当此属性为“空”时,未设置值。
最佳答案
您需要实现自定义 JsonConverter
并将其分配给 JsonProperty
属性的 TrimmingConverter
属性。有写客户TrimmingConverter
的例子 详细here .一旦你实现了与此类似的东西,你应该能够同时设置 NullValueHandling
和 ItemConverterType
属性。这将确保转换器将修剪字符串,如果它为 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/