NewtonSoft对象转json时,把 NULL 转 "" , 过滤 NULL, DateTime 时间类型去除 T

IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
// IsoDateTimeConverter timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss"};
string jsonStr = JsonConvert.SerializeObject(obj,Formatting.Indented,timeConverter);

NewtonSoft.Json NULL转空字符串
http://www.cnblogs.com/hetuan/articles/4565702.html

/// <summary>
/// 对DBNull的转换处理,此处只写了转换成JSON字符串的处理,JSON字符串转对象的未处理
/// </summary>
public class DBNullCreationConverter : JsonConverter
{
    /// <summary>
    /// 是否允许转换
    /// </summary>
    public override bool CanConvert(Type objectType)
    {
        bool canConvert = false;
        switch (objectType.FullName)
        {
            case "System.DBNull":

                canConvert = true;
                break;
        }
        return canConvert;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return existingValue;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(string.Empty);
    }

    public override bool CanRead
    {
        get
        {
            return false;
        }
    }
    /// <summary>
    /// 是否允许转换JSON字符串时调用
    /// </summary>
    public override bool CanWrite
    {
        get
        {
            return true;
        }
    }
}
IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
DBNullCreationConverter d = new DBNullCreationConverter();
timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
var json = JsonConvert.SerializeObject(ds.Tables, Newtonsoft.Json.Formatting.Indented, timeFormat, d);
posted @ 2019-05-19 11:22  Mouer404  阅读(770)  评论(0编辑  收藏  举报