3

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

sydur.rahman21
  • 169
  • 1
  • 2
  • 8
  • 1
    Hi there; please edit your question and post code, data and errors as text with the appropriate formatting. – Stefan Jun 01 '18 at 18:20
  • 1
    @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,. – Ryan Wilson Jun 01 '18 at 18:23
  • 1
    Possible duplicate of pretty print: https://stackoverflow.com/questions/9847564/how-do-i-get-asp-net-web-api-to-return-json-instead-of-xml-using-chrome#13277616 – Stefan Jun 01 '18 at 18:24
  • 1
    So you want it to return your Json prettified? Register your JsonMediaTypeFormatter with the Formatting = Formatting.Indented SerializerSetting in your WebApiConfig. – Jonathon Chase Jun 01 '18 at 18:25
  • 1
    Please refer this link. https://stackoverflow.com/questions/42566284/return-json-object-asp-net-webapi/42566346 – Isuru Lakshan Jun 01 '18 at 18:36
  • Try returning your List as json. Check this link - https://stackoverflow.com/questions/9777731/mvc-how-to-return-a-string-as-json – kaarthick raman Jun 01 '18 at 19:48

2 Answers2

5

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

    }
}
Jonathon Chase
  • 9,396
  • 21
  • 39
  • @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. – Jonathon Chase Jun 05 '18 at 19:41
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.

Christos Lytras
  • 36,310
  • 4
  • 80
  • 113
Debashish Saha
  • 318
  • 1
  • 12