Json.Net 如何将 null 反序列化为空字符串?

4
我有一个字符串属性在我的类中,例如:
        [DataMember]
        [JsonProperty(PropertyName = "email")]
        [StringLength(40, ErrorMessage = "The Mobile value cannot exceed 40 characters. ")]
        public string Email { get; set; }

在Convert.Deserialize过程中,如果JSON对象中没有设置某个属性的值,由于某种原因,我需要在该属性中使用空字符串而不是null。如何做到这一点?

1个回答

8
您可以使用 DefaultValue 属性。
将其装饰为:
[DataMember]
[JsonProperty(PropertyName = "email", DefaultValueHandling = DefaultValueHandling.Populate)]
[StringLength(40, ErrorMessage = "The Mobile value cannot exceed 40 characters. ")]
[DefaultValue("")]
public string Email { get; set; }

它不会在没有 [JsonProperty(PropertyName = "email",DefaultValueHandling = DefaultValueHandling.Populate)] 的情况下工作。 - Arbejdsglæde
@cleric - 感谢你的更新。是的,我错过了那个,已经有一段时间了,抱歉。 - Srikanth Venugopalan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接