NewtonSoft.Json NULL转空字符串
NewtonSoft.Json对需要转为JSON字符串的对象的NULL值以及DBNull是直接处理成NULL的。对DBNull 的JSON字符串对应需要空字符串。
/// <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 x = new DBNullCreationConverter(); timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss"; return JsonConvert.SerializeObject(ds.Tables, Newtonsoft.Json.Formatting.Indented, timeFormat, x);