Newtonsoft. JSON directly converts the null value of the object to be converted into a JSON string and dbnull into null. In our project, the JSON string of dbnull needs a null string.
So I studied the classes in the newtonsoft. JSON. Converters namespace.
This space is for some types of formatting Converters
So I wrote a class to inherit jsonconverter.
The Code is as follows:
/// <Summary> /// converts dbnull. Here, only the JSON string is converted, the JSON string to object is not processed // </Summary> public class dbnullcreationconverter: jsonconverter {// <summary> // whether conversion is allowed /// </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 >/// whether to call the function when converting a JSON string /// </Summary> Public override bool canwrite {get {return true ;}}}
Call
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);