The C # Web API return type is set to JSON in two ways _ practical tips

Source: Internet
Author: User
Tags serialization

When the Web API writes the API interface by default, it returns the serialization of your object and returns it as XML, so how do you get it back to JSON, and here are two ways:
Method One: (change Collocation method)

Locate the Global.asax file and add a sentence to the Application_Start () method:

Copy Code code as follows:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear ();

After modification:
Copy Code code as follows:

protected void Application_Start ()
{
Arearegistration.registerallareas ();
Webapiconfig.register (globalconfiguration.configuration);
Filterconfig.registerglobalfilters (globalfilters.filters);
Routeconfig.registerroutes (routetable.routes);
To return the API to JSON
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear ();
}

So the result returned is JSON type, but there is a bad place, if the result returned is string type, such as 123, the returned JSON will become "123";

The workaround is to customize the return type (the return type is Httpresponsemessage)
Copy Code code as follows:

Public httpresponsemessage postusername (user user)
{
String userName = user.username;
Httpresponsemessage result = new Httpresponsemessage {Content = new Stringcontent (username,encoding.getencoding ("UTF-8 ")," Application/json ")};
return result;
}

Method Two: (Balm method)

Method one to change the configuration, but also to handle the return value of string type of JSON, very troublesome, rather than the Web API in the automatic serialization of objects, the serialization of their own and then return
Copy Code code as follows:

Public httpresponsemessage postuser (user user)
{
JavaScriptSerializer serializer = new JavaScriptSerializer ();
String str = serializer. Serialize (user);
Httpresponsemessage result = new Httpresponsemessage {Content = new stringcontent (str, encoding.getencoding ("UTF-8"), "a Pplication/json ")};
return result;
}

Method Two is the method I recommend, in order not to write the code repeatedly in each interface, so the encapsulation as a way to use it is much more convenient.
Copy Code code as follows:

public static Httpresponsemessage Tojson (Object obj)
{
String str;
if (obj is String | | obj is Char)
{
str = obj. ToString ();
}
Else
{
JavaScriptSerializer serializer = new JavaScriptSerializer ();
str = serializer. Serialize (obj);
}
Httpresponsemessage result = new Httpresponsemessage {Content = new stringcontent (str, encoding.getencoding ("UTF-8"), "a Pplication/json ")};
return result;
}

Method Three: (the most troublesome method)

The simplest method, but the lethality is too large, all the returned XML format will be shot down, then method three can only let the API interface to kill XML, return JSON

First write a class that handles the return:
Copy Code code as follows:

public class Jsoncontentnegotiator:icontentnegotiator
{
Private ReadOnly Jsonmediatypeformatter _jsonformatter;

Public Jsoncontentnegotiator (Jsonmediatypeformatter formatter)
{
_jsonformatter = formatter;
}

Public Contentnegotiationresult Negotiate (type type, httprequestmessage request, Ienumerable<mediatypeformatter > formatters)
{
var result = new Contentnegotiationresult (_jsonformatter, New Mediatypeheadervalue ("Application/json"));
return result;
}
}

Locate the WebApiConfig.cs file in App_start and open the register (httpconfiguration config) method

Add the following code:
Copy Code code as follows:

var jsonformatter = new Jsonmediatypeformatter ();
Config. Services.replace (typeof (Icontentnegotiator), New Jsoncontentnegotiator (Jsonformatter));

Add the following code:
Copy Code code as follows:

public static void Register (Httpconfiguration config)
{
Config. Routes.maphttproute (
Name: "Defaultapi",
Routetemplate: "Api/{controller}/{action}/{id}",
defaults:new {id = routeparameter.optional}
);
var jsonformatter = new Jsonmediatypeformatter ();
Config. Services.replace (typeof (Icontentnegotiator), New Jsoncontentnegotiator (Jsonformatter));
}

Method three If the result returned is a string type, such as 123, the returned JSON becomes "123", and the solution is the same as method one.

In fact, the Web API will automatically convert the returned objects into XML and JSON two format coexistence, method One and method three is to kill the return of XML, and method two is custom return.

PS: About JSON operation, here we recommend a few more practical JSON online tools for your reference to use:

Online JSON code inspection, inspection, landscaping, formatting tools:
Http://tools.jb51.net/code/json

JSON Online formatting tool:
Http://tools.jb51.net/code/jsonformat

Online Xml/json Mutual Conversion tool:
Http://tools.jb51.net/code/xmljson

JSON code online Format/beautify/compress/edit/Convert tools:
Http://tools.jb51.net/code/jsoncodeformat

Online JSON compression/escape tool:

Http://tools.jb51.net/code/json_yasuo_trans

C Language Style/html/css/json code formatting landscaping Tools:
Http://tools.jb51.net/code/ccode_html_css_json

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.