Web Api not converting json empty strings values to null

送分小仙女□ 提交于 2020-01-14 04:00:09

问题


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:


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());


来源:https://stackoverflow.com/questions/23282514/web-api-not-converting-json-empty-strings-values-to-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!