WEBAPI Return JSON format optimization

Source: Internet
Author: User

First, set WEBAPI return JSON format

Under App_start, add the following code to the register of the Webapiconfig registration function register

Config. Formatters.remove (config. Formatters.xmlformatter);

Second, set the return JSON key value uniform to lowercase

Create a new class and inherit from Defaultcontractresolver, overriding the Resolvepropertyname method,

 Public class underlinesplitcontractresolver:defaultcontractresolver {     protectedoverride  String resolvepropertyname (string  PropertyName)     {         //return Camelcasetounderlinesplit (PropertyName);         return propertyname.tolower ();     } }

Adding configuration code in the Webapiconfig.register method

// use mixed case for JSON data. The same size as the property name. Output new underlinesplitcontractresolver ();
Three, there are two very unhappy problems in the returned JSON format.

Look at the picture:

The first question is a null string, and here also returns NULL, feeling Back "" feel a little better

The second problem, Lastupdate is the time format, this kind of formatting looks a bit uncomfortable, if it is "2016-03-25 17:19:17" feel better.

Resolved as follows:

In solving the second problem, our new class Underlinesplitcontractresolver overrides the Createproperties method:

 //Resolving API NULL and time format issues protected OverrideIlist<jsonproperty>createproperties (Type type, Memberserialization memberserialization) {returntype. GetProperties
. Select (P= { varJP =Base. CreateProperty (P, memberserialization); if(JP. PropertyType = =typeof(System.String)) JP. Valueprovider=NewNulltoemptystringvalueprovider (P); if(JP. Propertytype.tostring (). Contains ("System.DateTime") ) JP. Converter=NewIsodatetimeconverter () {DateTimeFormat ="YYYY-MM-DD HH:mm:ss" }; returnJP; }). ToList ();}
The Nulltoemptystringvalueprovider class inherits the Ivalueprovider code as follows:
    /// <summary>    ///resolving NULL problems returning JSON data/// </summary>     Public classNulltoemptystringvalueprovider:ivalueprovider {PropertyInfo _memberinfo;  PublicNulltoemptystringvalueprovider (PropertyInfo memberInfo) {_memberinfo=MemberInfo; }         Public ObjectGetValue (Objecttarget) {            Objectresult =_memberinfo.getvalue (target); //if (result = = null)//result = "";            if(_memberinfo.propertytype = =typeof(string) && result = =NULL) Result=""; returnresult; }         Public voidSetValue (ObjectTargetObjectvalue)        {_memberinfo.setvalue (target, value); }    }

The problem is resolved and the JSON returned is as follows:

Does it look more comfortable?

Four, tidy up the code

Create a new file InitAPI.cs with the following code:

   Public classInitapi { Public Static voidInit (httpconfiguration config) {//httpconfiguration config = globalconfiguration.configuration;CONFIG. Formatters.remove (config.            Formatters.xmlformatter); //Resolving circular reference problems with JSON serializationConfig. Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling =Newtonsoft.Json.ReferenceLoopHandling.Ignore; //use mixed case for JSON data.            Camel, but it is the lowercase form of the JavaScript first letter. //CONFIG.            Formatters.JsonFormatter.SerializerSettings.ContractResolver = new Camelcasepropertynamescontractresolver (); //use mixed case for JSON data. The same size as the property name. OutputConfig. Formatters.JsonFormatter.SerializerSettings.ContractResolver =NewUnderlinesplitcontractresolver (); }    }     Public classUnderlinesplitcontractresolver:defaultcontractresolver {protected Override stringResolvepropertyname (stringPropertyName) {            //return Camelcasetounderlinesplit (PropertyName);            returnPropertyname.tolower (); }        Private stringCamelcasetounderlinesplit (stringname) {            returnname.        ToLower (); }        //Resolving API NULL and time format issues        protected OverrideIlist<jsonproperty>createproperties (Type type, Memberserialization memberserialization) {returntype. GetProperties (). Select (P=                   {                       varJP =Base.                       CreateProperty (P, memberserialization); if(JP. PropertyType = =typeof(System.String)) JP. Valueprovider=NewNulltoemptystringvalueprovider (P); if(JP. Propertytype.tostring (). Contains ("System.DateTime") ) JP. Converter=NewIsodatetimeconverter () {DateTimeFormat ="YYYY-MM-DD HH:mm:ss" }; returnJP; }).        ToList (); }    }    /// <summary>    ///resolving NULL problems returning JSON data/// </summary>     Public classNulltoemptystringvalueprovider:ivalueprovider {PropertyInfo _memberinfo;  PublicNulltoemptystringvalueprovider (PropertyInfo memberInfo) {_memberinfo=MemberInfo; }         Public ObjectGetValue (Objecttarget) {            Objectresult =_memberinfo.getvalue (target); //if (result = = null)//result = "";            if(_memberinfo.propertytype = =typeof(string) && result = =NULL) Result=""; returnresult; }         Public voidSetValue (ObjectTargetObjectvalue)        {_memberinfo.setvalue (target, value); }    }
To call Initapi.init (config) directly in Webapiconfig, the code is as follows:
  Public Static classWebapiconfig { Public Static voidRegister (httpconfiguration config) {//Web API Configuration and Services//Web API RoutingCONFIG.            Maphttpattributeroutes (); Config. Routes.maphttproute (Name:"Defaultapi", Routetemplate:"Api/{controller}/{id}", defaults:New{id =routeparameter.optional});        initapi.init (config); }    }

End

WEBAPI Return JSON format optimization

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.