一佳一

记录像1+1一样简洁的代码

导航

Newtonsoft.Json 全局设置 json null转换为空(包含int)

Posted on 2024-08-01 11:47  一佳一  阅读(35)  评论(0编辑  收藏  举报
public class CustomDateConverter : IsoDateTimeConverter
    {
        public CustomDateConverter()
        {
            DateTimeFormat = "yyyy-MM-dd HH:mm:ss"; // 设定你想要的日期时间格式
        }
    }
    public class NullToEmptyStringConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            if (objectType.FullName == "System.DBNull")
            {
                return true;
            }
            return typeof(int).IsAssignableFrom(objectType);
            
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null || reader.Value.ToString() == "null")
            {
                return "";
            }
            return reader.Value;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null || value == DBNull.Value)
            {
                writer.WriteValue("");
            }
            else
            {
                writer.WriteValue(value.ToString());
            }
        }
    }
 var jsonsetting = new Newtonsoft.Json.JsonSerializerSettings()
            {
                DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore,
            };
            jsonsetting.Converters.Add(new CustomDateConverter());
            jsonsetting.Converters.Add(new NullToEmptyStringConverter());
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = jsonsetting;