Web Api未将JSON空字符串值转换为null

3

示例Json: {"Field1":"","Field2":null}.

在MVC中,默认情况下,Field1会转换为null。 我尝试了[DisplayFormat(ConvertEmptyStringToNull = true)]属性(这应该是默认设置),但没有任何变化。

我正在使用Web Api 2.1

你有什么想法吗?


请注意,MVC DisplayFormat 对 WebAPI 没有任何影响,它们是两个独立的框架。 - Yishai Galatzer
1个回答

14
在C#中,空字符串和null引用不是相同的概念。而底层的JSON实现库Json.NET决定避免进行自动转换。你可以添加下面的自定义转换器来解决这个问题。

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

你能解释一下为什么会出现堆栈溢出吗? - syclee
很好的问题,我不记得了,你可以尝试不带额外字段并捕获调用堆栈。 - Yishai Galatzer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接