在浏览了ASP.NET Core MVC (v2.1)的源代码和Newtonsoft.Json (v11.0.2)的源代码之后,我想出了以下解决方案。
首先,创建自定义JsonConverter
:
public class EmptyStringToNullJsonConverter : JsonConverter
{
public override bool CanRead => true;
public override bool CanWrite => false;
public override bool CanConvert(Type objectType)
{
return typeof(string) == objectType;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
string value = (string)reader.Value;
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException("Unnecessary because CanWrite is false. The type will skip the converter.");
}
}
然后,全局注册自定义转换器:
services
.AddMvc(.....)
.AddJsonOptions(options => options.SerializerSettings.Converters.Add(new EmptyStringToNullJsonConverter()))
或者,通过JsonConverterAttribute
. 例如:
public class Item
{
public int Value { get; set; }
[StringLength(50, MinimumLength = 3)]
[JsonConverter(typeof(EmptyStringToNullJsonConverter))]
public string Description { get; set; }
}