示例Json: {"Field1":"","Field2":null}.
在MVC中,默认情况下,Field1会转换为null。 我尝试了[DisplayFormat(ConvertEmptyStringToNull = true)]属性(这应该是默认设置),但没有任何变化。
我正在使用Web Api 2.1
你有什么想法吗?
示例Json: {"Field1":"","Field2":null}.
在MVC中,默认情况下,Field1会转换为null。 我尝试了[DisplayFormat(ConvertEmptyStringToNull = true)]属性(这应该是默认设置),但没有任何变化。
我正在使用Web Api 2.1
你有什么想法吗?
in C# an empty string is not the same as a null reference, and json.NET which is the underlying json implementation decided to avoid automatic conversions.
You can add the following custom converter to deal with that
public class EmptyToNullConverter : JsonConverter
{
private JsonSerializer _stringSerializer = new JsonSerializer();
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
string value = _stringSerializer.Deserialize<string>(reader);
if (string.IsNullOrEmpty(value))
{
value = null;
}
return value;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
_stringSerializer.Serialize(writer, value);
}
}
并且要在您的类中使用它,装饰您想要转换的属性
[JsonConverter(typeof(EmptyToNullConverter))]
public string FamilyName { get; set; }
你可以将此转换器添加到config.Formatters.JsonFormatter.SerializerSettings.Converters
中,它将适用于所有字符串。请注意,这需要私有成员_stringSerializer
,否则会出现堆栈溢出。如果直接修饰字符串属性,则不需要该成员。
在WebApiConfig.cs文件中添加以下行:
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new EmptyToNullConverter());