不使用datamember属性的json序列化程序NullValueHandling [英] json serializer NullValueHandling without use datamember attribute

查看:67
本文介绍了不使用datamember属性的json序列化程序NullValueHandling的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Web api项目中,现在我正在跳过空值.因此,返回json会忽略null值并显示属性.

In my Web api project, Right now I'm skipping null values. therefore, the return json ignores null values and prints the property.

在Global.asax文件中:

In Global.asax file:

//manage the null in the response
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;

但是,我想将空值替换为-".但是,我不想为每个属性使用数据成员属性...

However, I want to replace the null values by "-". but, i dont want to use data member attribute for each property...

[DefaultValue("-")]. 

我的项目中有10个以上的类...所以,这不是最优雅的解决方案.

i have more than 10 classes in my project... so, It is not the most elegant solution.

我希望这是一个简单的解决方案,并且适用于任何转换,就像Global.asax中的空值一样

I wish were a simple solution and apply to any conversion, as does with null values from the Global.asax

示例.

public class User
{
    public string user { get; set; }

    public string name { get; set; }

    public string dni { get; set; }
}

当所有数据都存在时,我的服务返回

when exists all data, my service return

{
  "user": "usertest",
  "name": "nametest",
  "dni": "123456789"
}

但是,当dni不存在时,请回答

But, when dni, doesn't exists, respond this

{
  "user": "usertest",
  "name": "nametest",
  "dni": ""
}

所以,我想回应如下

{
  "user": "usertest",
  "name": "nametest",
  "dni": "-"
}

推荐答案

您可以使用自定义的IContractResolver进行处理.解析程序可以对每个字符串属性应用IValueProvider,然后将其处理空值到-的转换(如果要反序列化相同的JSON,则返回该值).

You can handle this with a custom IContractResolver. The resolver can apply an IValueProvider to each and every string property, which would then handle the conversion of null values to - (and back, if you are deserializing the same JSON).

以下是解析器所需的代码:

Here is the code you would need for the resolver:

public class NullStringReplacementResolver : DefaultContractResolver
{
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        IList<JsonProperty> props = base.CreateProperties(type, memberSerialization);

        // Attach a NullStringReplacementProvider instance to each string property
        foreach (JsonProperty prop in props.Where(p => p.PropertyType == typeof(string)))
        {
            PropertyInfo pi = type.GetProperty(prop.UnderlyingName);
            if (pi != null)
            {
                prop.ValueProvider = new NullStringReplacementProvider(pi);
            }
        }

        return props;
    }

    protected class NullStringReplacementProvider : IValueProvider
    {
        PropertyInfo targetProperty;

        public NullStringReplacementProvider(PropertyInfo targetProperty)
        {
            this.targetProperty = targetProperty;
        }

        // GetValue is called by Json.Net during serialization.
        // The target parameter has the object from which to read the string;
        // the return value is the string that gets written to the JSON
        public object GetValue(object target)
        {
            // if the value of the target property is null, replace it with "-"
            string s = (string)targetProperty.GetValue(target);
            return (s == null ? "-" : s);
        }

        // SetValue gets called by Json.Net during deserialization.
        // The value parameter has the original value read from the JSON;
        // target is the object on which to set the value.
        public void SetValue(object target, object value)
        {
            // if the value in the JSON is "-" replace it with null
            string s = (string)value;
            targetProperty.SetValue(target, s == "-" ? null : s);
        }
    }
}

要使用自定义解析器,需要将其添加到序列化和反序列化过程中使用的JsonSerializerSettings中.如果使用的是ASP.NET Web API,则可以通过将以下内容添加到Global.asax.cs中的Application_Start方法中来做到这一点:

To use the custom resolver, you need to add it to the JsonSerializerSettings that are used during serialization and deserialization. If you're using ASP.NET Web API, you can do that by adding the following to the Application_Start method in Global.asax.cs:

var config = GlobalConfiguration.Configuration;
var settings = config.Formatters.JsonFormatter.SerializerSettings;
settings.ContractResolver = new NullStringReplacementResolver();

提琴: https://dotnetfiddle.net/FVA3p8

这篇关于不使用datamember属性的json序列化程序NullValueHandling的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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