网页API未进行转换的json空字符串值为null [英] Web Api not converting json empty strings values to null

查看:685
本文介绍了网页API未进行转换的json空字符串值为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如JSON:
{字段1:,字段2:空}

Example Json: {"Field1":"","Field2":null}.

在MVC中,字段1将被默认转换为null。
我试过[DisplayFormat(ConvertEmptyStringToNull =真)]属性,(这应该是默认反正),并没有发挥作用。

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.

我使用的网页API 2.1

I'm using Web Api 2.1

任何想法?

推荐答案

一是空字符串不为空,且json.NET这是底层的JSON实现不应该做的自动转换。

First empty string is not null, and json.NET which is the underlying json implementation should not do auto 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; }

您可以将此转换器添加到 config.Formatters.JsonFormatter.SerializerSettings.Converters ,它将适用于所有的字符串代替。请注意,它需要的私有成员_stringSerializer否则将计算器。如果你只是直接装点字符串属性的成员不是必需的。

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.

在WebApiConfig.cs添加以下行:

in WebApiConfig.cs add the following line:

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new EmptyToNullConverter());

这篇关于网页API未进行转换的json空字符串值为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆