How to Use newtonsoft. JSON jsconverter

Source: Internet
Author: User

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);

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.