JsonConvert JsonSerializerSettings Json 中 Null 替换为空字符串

发布时间 2023-10-09 11:26:29作者: cclon

 

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Logistics.Utils
{
    public class NullToEmptyStringResolver :DefaultContractResolver
    {
        protected override IList<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 : IValueProvider
    {
        PropertyInfo _MemberInfo;
        public NullToEmptyStringValueProvider(PropertyInfo memberInfo)
        {
            _MemberInfo = memberInfo;
        }

        public object GetValue(object target)
        {
            object result = _MemberInfo.GetValue(target);
            if (result == null && _MemberInfo.PropertyType.ToString() == "System.String") result = "";
            return result;

        }

        public void SetValue(object target, object value)
        {
            _MemberInfo.SetValue(target, value);
        }
    }

}

 

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Logistics.Utils
{
    public class NewtonsoftHelper
    {
        public static string ToJson<T>(T obj, bool isSet = false)
        {
            if (obj == null) return null;

            if (isSet)
            {
                var settings = new JsonSerializerSettings
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,//这种方式指定忽略循环引用,是在指定循环级数后忽略,返回的json数据中还是有部分循环的数据
                    DateFormatString = "yyyy-MM-dd HH:mm:ss",
                    //ContractResolver = new CamelCasePropertyNamesContractResolver(),//json中属性开头字母小写的驼峰命名
                    //NullValueHandling = NullValueHandling.Ignore,//空值处理 忽略序列化
                    ContractResolver = new NullToEmptyStringResolver(),

                };
 

                return JsonConvert.SerializeObject(obj, settings);
            }
            else {
                return JsonConvert.SerializeObject(obj);
            }
       
        }

        public static T ToObject<T>(string jsonString)
        {
            if (string.IsNullOrEmpty(jsonString)) return default(T);
            return JsonConvert.DeserializeObject<T>(jsonString);
        }
    }
}