首页 > 其他分享 >Newtonsoft.Json将可空类型转换为空字符串(支持所有类型)

Newtonsoft.Json将可空类型转换为空字符串(支持所有类型)

时间:2022-10-28 12:12:43浏览次数:55  
标签:类型转换 Newtonsoft string settings value Json propertyInfo new public

第一步:json自定义解析协议

    /// <summary>
    /// json自定义解析协议
    /// </summary>
    public class SpecialJsonContractResolver : DefaultContractResolver
    {
        protected override IValueProvider CreateMemberValueProvider(MemberInfo member)
        {
            if (member.MemberType == MemberTypes.Property)
            {
                var pi = (PropertyInfo)member;
                if (pi.PropertyType == typeof(string) || pi.PropertyType == typeof(DateTime) || pi.PropertyType == typeof(DateTime?))
                {
                    return new NullableJsonValueProvider(pi);
                }
            }
            return base.CreateMemberValueProvider(member);
        }
    }
    
/// <summary> ///空值序列化提供程序 /// </summary> public class NullableJsonValueProvider : IValueProvider { private static readonly string _defaultValue = string.Empty; private readonly PropertyInfo _propertyInfo; public NullableJsonValueProvider(PropertyInfo propertyInfo) { _propertyInfo = propertyInfo; } public void SetValue(object target, object value) { _propertyInfo.SetValue(target, value); } public object GetValue(object target) { return _propertyInfo.GetValue(target) ?? _defaultValue; } }

  

 第二步:空值处理(以时间类型为例)

 public class DateTimeFormatConverter : IsoDateTimeConverter
    {
        private static readonly string strEmpty = string.Empty;
        public DateTimeFormatConverter(string format)
        {
            DateTimeFormat = format;
        }

        /// <summary>
        /// 重载序列化方法
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="value"></param>
        /// <param name="serializer"></param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null || value.Equals("") || value.Equals(DateTime.MinValue))
            {
                writer.WriteValue(strEmpty);
            }
            else
            {
                base.WriteJson(writer, value, serializer);
            }
        }
    }

第三步:使用

        public string TestJson()
        {
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.Converters.Add(new DecimalDigitsConvert());//只处理decimal类型的属性         
            settings.Converters.Add(new DateTimeFormatConverter("yyyy/MM/dd"));//默认时间格式处理        
            settings.ContractResolver = new SpecialJsonContractResolver(); //自定义解析协议  

            string json = JsonConvert.SerializeObject(new Models.StudentInfo.StudentInfo_ClassInfo() { ClassName = "班级名称" }, settings);
            return json;
        }

  

  

标签:类型转换,Newtonsoft,string,settings,value,Json,propertyInfo,new,public
From: https://www.cnblogs.com/5tomorrow/p/16835660.html

相关文章