[RESOLVED]how to receive a json response instead of xml

how can I get a json response instead of XML when calling a web API using mvc??

In WebApiconfig the Register method as below 

 public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "MobileApp/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            //config.Formatters.Clear();
           config.Formatters.Add(new JsonMediaTypeFormatter());
           // config.Formatters.Add(new BsonMediaTypeFormatter());
        }

page source not found.should I change anything in the routes?

hi you can do one thing,

config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());

You have to add formatters

config.Formatters.Add(new JsonMediaTypeFormatter());

In Web API 2.2,  JSON is a default functionality i.e. a Web API method can receive JSON formatted data from client  as well as send JSON formatted data back to the client in its response.

"Web API has built-in support for XML, JSON, BSON, and form-urlencoded data, and you can support additional media types by writing a media formatter.".

So for JSON you don’t have to write any special code in C# since that is already there in Web API, but you need to make sure that you send an appropriate ajax request from jQuery.

For JSON response when using jQuery, you should use jQuery AJAX request as below with
dataType: "json". Note the attribute ‘dataType’ that tells the Web API about what is expected in Web API’s response. If you mention dataType as xml i.e. dataType:xml,  then Web API method will return data formatted as XML and not as JSON.

function CallAWebAPIMethod() {
            var data = {
                productId: 100,
                productDescription: "Product 123
            }
            $.ajax({
                url: 'api/MyWebApi',
                type: 'PUT',
                data: JSON.stringify(data),
                contentType: "application/json",
                dataType:"json",
                success: function (data) {
                    alert(data);
                },
                error: function (x, y, z) {
                    alert(x + 'n' + y + 'n' + z);
                }
            });
        }

If you are calling Web API from .Net code and not from jQuery
then use C# code like below to get back JSON formatted data. Note the last line of code line which is telling the Web API to return JSON formatted data.

using (var client = new HttpClient())
{
    // New code:
    client.BaseAddress = new Uri("http://localhost:9000/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}

Leave a Reply