C# Newtonsoft.Json null 转空值{} 把对象null转换{}为JSON字符串

/// <summary>
        /// 把对象null转换{}为JSON字符串
        /// </summary>
        /// <param name="o">对象</param>
        /// <returns>JSON字符串</returns>
        public static string ObjectToJsonNullValue(this object data)
        {
            try
            {
                if (data == null)
                {
                    return null;
                }
                var jsonSetting = new JsonSerializerSettings();
                jsonSetting.ContractResolver = new NullToEmptyStringResolver();
                var json = JsonConvert.SerializeObject(data, jsonSetting);
                return json;
            }
            catch (Exception)
            {

                return null;
            }
        }

        public class NullToEmptyStringResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
        {
            protected override IList<Newtonsoft.Json.Serialization.JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
            {
                return type.GetProperties()
                        .Select(p => {
                            var jp = base.CreateProperty(p, memberSerialization);
                            jp.ValueProvider = new NullToEmptyStringValueProvider(p);
                            return jp;
                        }).ToList();
            }
        }
        public class NullToEmptyStringValueProvider : Newtonsoft.Json.Serialization.IValueProvider
        {
            PropertyInfo _MemberInfo;
            public NullToEmptyStringValueProvider(PropertyInfo memberInfo)
            {
                _MemberInfo = memberInfo;
            }
            public object GetValue(object target)
            {
                object result = _MemberInfo.GetValue(target);
                if (_MemberInfo.PropertyType.BaseType == typeof(object)) 
                {
                    if (_MemberInfo.PropertyType != typeof(string)&&result==null) 
                    {
                        result =new Newtonsoft.Json.Linq.JObject();
                    }
                }
                return result;
            }
            public void SetValue(object target, object value)
            {
                _MemberInfo.SetValue(target, value);
            }
        }

 

posted @ 2023-02-08 19:48  LuoCore  阅读(687)  评论(0编辑  收藏  举报