Read Asp.Net Web API data in JSON format

By default, Asp.Net WEB API returns data in XML format, as shown in my previous articles. In this article, we discuss how we can return the data in JSON format instead of XML. In C#, we use Newtonsoft.Json to convert any format data into JSON.

Method-1

Let’s change our code to return the data in JSON format, as shown below.

using CompanyRestAPI.Models;
using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Web.Http; 

namespace CompanyRestAPI.Controllers
{
    public class EmployeesController : ApiController
    {
        // GET: Employees
        [Route("api/employees/getemployees")]
        [HttpGet]
        public HttpResponseMessage GetEmployees()
        {
            try
            {
                var employees = Company.GetEmployees(); 

                var response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new StringContent(JsonConvert.SerializeObject(employees));
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                return response;
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
            }
        } 

        // GET: Employee based on id
        [Route("api/employees/getemployee")]
        [HttpGet]
        public HttpResponseMessage GetEmployee(int id)
        {
            try
            {
                var employee = Company.GetEmployee(id); 

                var response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new StringContent(JsonConvert.SerializeObject(employee));
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                return response;
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
            }
        } 

        // GET: Employee based on id and name
        [Route("api/employees/getemployee")]
        [HttpGet]
        public HttpResponseMessage GetEmployee(int id, string name)
        {
            try
            {
                var employee = Company.GetEmployee(id, name); 

                var response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new StringContent(JsonConvert.SerializeObject(employee));
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                return response;
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
    }
}

Run the application and request the URL https://localhost:44358/api/employees/getemployee?id=1&name=John; it displays the data in JSON format, as shown below. GetEmployees() method data also will display in JSON format using https://localhost:44358/api/employees/getemployees URL.

Method-2

In the above method, we have made a lot of code changes to display the data in JSON format. For example, if you want to return data only in JSON format for all your API methods, then declare JSON formatter in the WebApiConfig Register() method instead of making code changes for all of your action methods as shown below.

using System.Net.Http.Headers;
using System.Web.Http; 

namespace CompanyRestAPI
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Web API routes
            config.MapHttpAttributeRoutes(); 

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        }
    }
}

Here we are adding the JSON formatter to config settings.

Method-3

We can return the data in JSON format by disabling the XML formatter. As we know, Asp.Net Web API supports only XML and JSON formats. If we remove the XML formatter, it displays the data in JSON format only. So , make the code changes as shown below.

using System.Net.Http.Headers;
using System.Web.Http; 

namespace CompanyRestAPI
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Web API routes
            config.MapHttpAttributeRoutes(); 

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
        }
    }
}

Run the application by using any one of the above two methods and request for GetEmployees() method (https://localhost:44358/api/employees/getemployees), it displays the data as shown below.

                                   

                                                                                                                   CompanyRestAPI-3.zip (55.60 mb)