Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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???

like image 618
sydur.rahman21 Avatar asked Oct 27 '25 19:10

sydur.rahman21


2 Answers

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});
            }
        }

    }
}
like image 60
Jonathon Chase Avatar answered Oct 30 '25 10:10

Jonathon Chase


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.

like image 23
Debashish Saha Avatar answered Oct 30 '25 10:10

Debashish Saha