3

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?

1
  • Note that the MVC DisplayFormat have no effect on WebAPI, these are two independent frameworks. Commented Dec 5, 2017 at 2:28

1 Answer 1

14

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());
Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain why it stack overflows?
Great question, I do not recall, you can just try it without the extra field and capture the callstack

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.