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 {     protected override 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 Config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = 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:

Resolves API NULL and time format issues protected override ilist<jsonproperty> Createproperties (type type, memberserialization memberserialization) {     return type. GetProperties
. Select (p = = { var jp = base. CreateProperty (P, memberserialization); if (JP. PropertyType = = typeof (System.String)) JP. Valueprovider = new Nulltoemptystringvalueprovider (p); if (JP. Propertytype.tostring (). Contains ("System.DateTime")) JP. Converter = new Isodatetimeconverter () {DateTimeFormat = "yyyy-mm-dd HH:mm:ss"}; return JP; }). ToList ();}
The Nulltoemptystringvalueprovider class inherits the Ivalueprovider code as follows:
    <summary>///    resolve return JSON data null problem///    </summary> public    class Nulltoemptystringvalueprovider:ivalueprovider    {        PropertyInfo _memberinfo;        Public Nulltoemptystringvalueprovider (PropertyInfo memberInfo)        {            _memberinfo = memberInfo;        }        public object GetValue (object target)        {            Object result = _memberinfo.getvalue (target);            if (result = = NULL)             //    result = "";            if (_memberinfo.propertytype = = typeof (string) && result = = null)                result = "";            return result;        }        public void SetValue (object target, object value)        {            _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 class Initapi {public static void Init (Httpconfiguration config) {//httpconfigurati            on config = globalconfiguration.configuration; Config. Formatters.remove (config.            Formatters.xmlformatter); Resolves a circular reference issue in JSON serialization config. 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. Output CONFIG.        Formatters.JsonFormatter.SerializerSettings.ContractResolver = new Underlinesplitcontractresolver (); }} public class Underlinesplitcontractresolver:defaultcontractresolver {protected override string Reso            Lvepropertyname (String propertyname) {//return camelcasetounderlinesplit (PropertyName);return Propertyname.tolower (); private string Camelcasetounderlinesplit (string name) {return name.        ToLower (); }//Resolve API NULL and time format issues protected override ilist<jsonproperty> Createproperties (type type, memberserial ization memberserialization) {return type. GetProperties (). Select (P = = {var JP = base.                       CreateProperty (P, memberserialization); if (JP. PropertyType = = typeof (System.String)) JP.                       Valueprovider = new Nulltoemptystringvalueprovider (p); if (JP. Propertytype.tostring (). Contains ("System.DateTime")) JP.                       Converter = new Isodatetimeconverter () {DateTimeFormat = "yyyy-mm-dd HH:mm:ss"};                   return JP; }).        ToList (); }}///<summary>//Resolve return JSON data null problem///</summary> public class NulltoempTystringvalueprovider:ivalueprovider {PropertyInfo _memberinfo;        Public Nulltoemptystringvalueprovider (PropertyInfo memberInfo) {_memberinfo = MemberInfo;            public object GetValue (object target) {object result = _memberinfo.getvalue (target);            if (result = = NULL)//result = "";            if (_memberinfo.propertytype = = typeof (string) && result = = NULL) result = "";        return result;        } public void SetValue (object target, object value) {_memberinfo.setvalue (target, value); }    }
To call Initapi.init (config) directly in Webapiconfig, the code is as follows:
public static class Webapiconfig    {public        static void Register (httpconfiguration config)        {            //Web API Configuration and service            //Web API Route            config. 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.