How to return JSON Array in ASP.NET Web API C#

11,574

Solution 1

If you want to return prettified JSON by default, you'll want to configure the media type formatter in your WebApiConfig.

As a quick example, in a WebApiConfig.Register(HttpConfiguration config) method,

config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter() {
    SerializerSettings = new JsonSerializerSettings {
        Formatting = Formatting.Indented
    }
};

This is also where you can set other default options, such as serializing properties to camelCase (CamelCasePropertyNamesContractResolver), or excluding the output of null properties (NullValueHandling.Ignore).

To add your List to a new object that has a single property, RainfallAreaAVG, I would do the following:

  • Change the return type on your controller actions to IHttpActionResult

  • Return an anonymous object with your new property name's value set to the list you wish to return

Your controller could end up looking like this:

namespace RainfallService.Controllers
{
    public class DistAVGController : ApiController
    {

        [HttpGet]
        public IHttpActionResult GetRainfall(string distBbsID, string entryDate)
        {
            using (var db = new Farmer_WebEntities())
            {
                var rainfalls = db.SP_GetRainfallByDistDateAVG(distBbsID, entryDate).ToList();
                return Ok(new {RainfallAreaAVG = rainfalls});
            }
        }

        [HttpGet]
        public IHttpActionResult GetRainfall(string distBbsID, string entryDate,string type)
        {
            using (var db = new Farmer_WebEntities())
            {
                var rainfalls = db.SP_GetRainfallByDistDateAVGDetails(distBbsID, entryDate).ToList();
                return Ok(new {RainfallAreaAVG = rainfalls});
            }
        }

    }
}

Solution 2

public class ActualRainfall
{
    public List<Rainfallareaavg> RainfallAreaAVG { get; set; }
}

public class Rainfallareaavg
{
    public string AreaBbsID { get; set; }
    public string DistCount { get; set; }
    public string Amount { get; set; }
    public string Hail { get; set; }
    public List<Arealdetail> ArealDetails { get; set; }
}

public class Arealdetail
{
    public string DistBbsID { get; set; }
    public string SubDistCount { get; set; }
    public string Amount { get; set; }
    public string Hail { get; set; }
    public List<Distdetail> DistDetails { get; set; }
}

public class Distdetail
{
    public string SubDistBbsID { get; set; }
    public string Amount { get; set; }
    public string Hail { get; set; }
    public string Date { get; set; }
}

Make this your model class to set the return type of GetRainFall() to be this model class.

GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());

in WebApiConfig.cs, or While Making the API request pass Application/json in the header.

Share:
11,574
sydur.rahman21
Author by

sydur.rahman21

Software engineer with more than 08 (Eight) years of experience on Enterprise System Analysis and Design using C#.Net. Expertise in C#, ASP.Net, ASP.Net MVC, ASP.Net Core, Angular, ASP.Net Web API, WCF, MS Sql Server, Oracle, Crystal Report, SVN Client, SVN Server. A Remarkable experience on Enterprise Resource Planning (ERP), Enterprise Management System (EMaS), Core Banking Solution (CBS), Financial Information System (FIS), Microfinance Management System (MMS) etc. Exclusive experience on stand alone project development, complicated database design and development, configure server in IIS7, IIS8 and IIS10.

Updated on June 05, 2022

Comments

  • sydur.rahman21
    sydur.rahman21 almost 2 years

    I want to return (display in the web browser) json array in below format.

    {
        "RainfallAreaAVG": [
        {
            "AreaBbsID": "18",
            "DistCount": "1",
            "SubDistCount": "2",
            "Amount": "14",
            "Hail": "14",
            "ArealDetails": [
                    {
                        "DistBbsID": "101",
                        "SubDistCount": "2",
                        "Amount": "14",
                        "Hail": "14",
                        "SubDistCount": "2",
                        "DistDetails": [
                            {
                                "SubDistBbsID": "101",
                                "Amount": "14",
                                "Hail": "2",
                                "Date": "2011-06-13"
                            },
                            {
                                "SubDistBbsID": "102",
                                "Amount": "10",
                                "Hail": "0",
                                "Date": "2011-06-13"
                            }
                        ]
                    }
                ]
            }
        ]
    }
    

    I am using asp.net web API (MVC) in c# and Entity Framework 5.0, ADO.Net Entity Data Model as my model.

    I'm using stored procedure to get data from sql server DB:

    enter image description here

    At present I'm using code below in my controller

    namespace RainfallService.Controllers
    {
        public class DistAVGController : ApiController
        {
    
            [HttpGet]
            public List<SP_GetRainfallByDistDateAVG_Result> GetRainfall(string distBbsID, string entryDate)
            {
                using (var db = new Farmer_WebEntities())
                {
                    var rainfalls = db.SP_GetRainfallByDistDateAVG(distBbsID, entryDate).ToList();
                    return rainfalls;
                }
            }
    
            [HttpGet]
            public List<SP_GetRainfallByDistDateAVGDetails_Result> GetRainfall(string distBbsID, string entryDate,string type)
            {
                using (var db = new Farmer_WebEntities())
                {
                    var rainfalls = db.SP_GetRainfallByDistDateAVGDetails(distBbsID, entryDate).ToList();
                    return rainfalls;
                }
            }
    
        }
    }
    

    And my output is like below which I don't want.

    For Average For Details

    ADO.Net Entity Data Model using like below enter image description here

    Model Classes I'm using

    namespace RainfallService
    {
        using System;
    
        public partial class SP_GetRainfallByDistDateAVG_Result
        {
            public string AreaBbsId { get; set; }
            public string DistBbsID { get; set; }
            public Nullable<int> SubDistCount { get; set; }
            public Nullable<decimal> Amount { get; set; }
            public Nullable<int> Hail { get; set; }
        }
    }
    

    And

    namespace RainfallService
    {
        using System;
    
        public partial class SP_GetRainfallByDistDateAVGDetails_Result
        {
            public string AreaBbsId { get; set; }
            public string DistBbsID { get; set; }
            public string SubDistBbsId { get; set; }
            public Nullable<decimal> Amount { get; set; }
            public Nullable<int> Hail { get; set; }
        }
    }
    

    My WebApiConfig.cs as below

    namespace RainfallService
    {
        public class WebApiConfig
        {       
            public static void Register(HttpConfiguration config)
            {
                // Web API configuration and services
    
                EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
                config.EnableCors(cors);
    
                // Web API routes
                config.MapHttpAttributeRoutes();
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
    
                config.Formatters.Remove(config.Formatters.XmlFormatter);
                //config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
                //var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
                //jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            }
        }
    }
    

    Can anybody help me please???

    • Stefan
      Stefan almost 6 years
      Hi there; please edit your question and post code, data and errors as text with the appropriate formatting.
    • Ryan Wilson
      Ryan Wilson almost 6 years
      @Stefan It looks to me like he needs a new class which can house the results of his queries, in his DB example it looks like he has 3 procs being executed and returned as a dataset,.
    • Stefan
      Stefan almost 6 years
      Possible duplicate of pretty print: stackoverflow.com/questions/9847564/…
    • Jonathon Chase
      Jonathon Chase almost 6 years
      So you want it to return your Json prettified? Register your JsonMediaTypeFormatter with the Formatting = Formatting.Indented SerializerSetting in your WebApiConfig.
    • Isuru Lakshan
      Isuru Lakshan almost 6 years
    • kaarthick raman
      kaarthick raman almost 6 years
      Try returning your List<obj> as json. Check this link - stackoverflow.com/questions/9777731/…
  • sydur.rahman21
    sydur.rahman21 almost 6 years
    How about the controller class?
  • Jonathon Chase
    Jonathon Chase almost 6 years
    @sydur.rahman21 I've updated this answer with an example implementation of your controller for handling encapsulating your list as the value of a json property.