码迷,mamicode.com
首页 > Web开发 > 详细

Net Core 下 Newtonsoft.Json 转换字符串 null 替换成string.Empty

时间:2019-01-23 01:29:21      阅读:417      评论:0      收藏:0      [点我收藏+]

标签:字符串   newton   tps   ima   字符   gre   empty   eof   ring   

原文:Net Core 下 Newtonsoft.Json 转换字符串 null 替换成string.Empty

 public class NullToEmptyStringResolver : DefaultContractResolver
    {
        /// <summary>
        /// 创建属性
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="memberSerialization">序列化成员</param>
        /// <returns></returns>
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            return type.GetProperties()
                .Select(x =>
                {
                    var property = CreateProperty(x, memberSerialization);
                    property.ValueProvider = new NullToEmptyStringValueProvider(x);
                    return property;
                }).ToList();
        }

        /// <inheritdoc />
        /// <summary>
        /// 小写
        /// </summary>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        protected override string ResolvePropertyName(string propertyName)
        {
            return propertyName.ToLower();
        }
    }
public class NullToEmptyStringValueProvider : IValueProvider
    {
        private readonly PropertyInfo _memberInfo;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="memberInfo"></param>
        public NullToEmptyStringValueProvider(PropertyInfo memberInfo)
        {
            _memberInfo = memberInfo;
        }

        /// <inheritdoc />
        /// <summary>
        /// 获取Value
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        public object GetValue(object target)
        {
            var result = _memberInfo.GetValue(target);
            if (_memberInfo.PropertyType == typeof(string) && result == Convert.DBNull)
            {
                result = string.Empty;
            }

            return result;

        }

        /// <inheritdoc />
        /// <summary>
        /// 设置Value
        /// </summary>
        /// <param name="target"></param>
        /// <param name="value"></param>
        public void SetValue(object target, object value)
        {
            _memberInfo.SetValue(target, value);
        }
    }

 技术分享图片

 

Net Core 下 Newtonsoft.Json 转换字符串 null 替换成string.Empty

标签:字符串   newton   tps   ima   字符   gre   empty   eof   ring   

原文地址:https://www.cnblogs.com/lonelyxmas/p/10306833.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!