Reputation: 511
Example Json: {"Field1":"","Field2":null}.
In MVC, Field1 would be converted to null by default. I tried the [DisplayFormat(ConvertEmptyStringToNull = true)] attribute, (which should be the default anyway) and it did not make a difference.
I'm using Web Api 2.1
Any ideas?
Upvotes: 3
Views: 6492
Reputation: 8862
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);
}
}
and to use it in your class decorate the properties you want to convert with
[JsonConverter(typeof(EmptyToNullConverter))]
public string FamilyName { get; set; }
You can add this converter to the config.Formatters.JsonFormatter.SerializerSettings.Converters
and it will apply to all strings instead. Note that it required the private member _stringSerializer otherwise it will stackoverflow. The member is not required if you just decorate the string property directly.
in WebApiConfig.cs add the following line:
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new EmptyToNullConverter());
Upvotes: 14