C# 如何在ASP.NET Web API C中返回JSON数组#

C# 如何在ASP.NET Web API C中返回JSON数组#,c#,arrays,json,asp.net-web-api,C#,Arrays,Json,Asp.net Web Api,我想以下面的格式返回(在web浏览器中显示)json数组 { "RainfallAreaAVG": [ { "AreaBbsID": "18", "DistCount": "1", "SubDistCount": "2", "Amount": "14", "Hail": "14", "ArealDetails": [ {

我想以下面的格式返回(在web浏览器中显示)json数组

{
    "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"
                        }
                    ]
                }
            ]
        }
    ]
}
我在c#中使用asp.NETWebAPI(MVC),实体框架5.0,ADO.net实体数据模型作为我的模型

我正在使用存储过程从sql server DB获取数据:

目前,我正在控制器中使用下面的代码

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

    }
}
名称空间RainfallService.Controllers
{
公共类DistAVGController:ApiController
{
[HttpGet]
公共列表getRainsion(字符串distBbsID,字符串entryDate)
{
使用(var db=new Farmer\u WebEntities())
{
var rainfalls=db.SP_GetRainfallByDistDateAVG(distBbsID,entryDate).ToList();
回归降雨;
}
}
[HttpGet]
公共列表getRainsion(字符串distBbsID、字符串entryDate、字符串类型)
{
使用(var db=new Farmer\u WebEntities())
{
var rainfalls=db.SP_GetRainfallByDistDateAVGDetails(distBbsID,entryDate.ToList();
回归降雨;
}
}
}
}
我的输出值低于我不想要的值

使用ADO.Net实体数据模型,如下所示

我正在使用的模型类

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; }
    }
}
名称空间Rainfall服务
{
使用制度;
公共部分类SP_GetRainfallByDistDateAVG_结果
{
公共字符串AreaBbsId{get;set;}
公共字符串DistBbsID{get;set;}
公共可为空的子列表计数{get;set;}
公共可空金额{get;set;}
公共可为空的Hail{get;set;}
}
}

名称空间Rainfall服务
{
使用制度;
公共部分类SP_GetRainfallByDistDateAVGDetails_结果
{
公共字符串AreaBbsId{get;set;}
公共字符串DistBbsID{get;set;}
公共字符串substbbsid{get;set;}
公共可空金额{get;set;}
公共可为空的Hail{get;set;}
}
}
我的WebApiConfig.cs如下

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();
        }
    }
}
名称空间Rainfall服务
{
公共类WebApiConfig
{       
公共静态无效寄存器(HttpConfiguration配置)
{
//Web API配置和服务
EnableCorsAttribute cors=新的EnableCorsAttribute(“*”、“*”、“*”);
配置使能cors(cors);
//Web API路由
config.maphttpAttribute路由();
config.Routes.MapHttpRoute(
名称:“DefaultApi”,
routeTemplate:“api/{controller}/{id}”,
默认值:新建{id=RouteParameter.Optional}
);
config.Formatters.Remove(config.Formatters.XmlFormatter);
//config.Formatters.JsonFormatter.SerializerSettings.Formatting=Newtonsoft.Json.Formatting.Indented;
//var jsonFormatter=config.Formatters.OfType().First();
//jsonFormatter.SerializerSettings.ContractResolver=新的CamelCasePropertyNamesContractResolver();
}
}
}

有人能帮我吗?

如果您想在默认情况下返回经过修饰的JSON,您需要在WebApiConfig中配置媒体类型格式化程序

举个简单的例子,在WebApiConfig.Register(HttpConfiguration-config)方法中

这也是您可以设置其他默认选项的地方,例如将属性序列化为camelCase(CamelCasePropertyNamesContractResolver),或排除空属性的输出(NullValueHandling.Ignore)

要将列表添加到具有单个属性的新对象中,
Rainfallreaavg
,我将执行以下操作:

  • 将控制器操作的返回类型更改为IHttpActionResult

  • 返回一个匿名对象,将新属性名的值设置为要返回的列表

您的控制器可能最终看起来像这样:

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

    }
}
公共类实际降雨量
{
公共列表Rainfallreaavg{get;set;}
}
公共类RainfallareAvg
{
公共字符串AreaBbsID{get;set;}
公共字符串DistCount{get;set;}
公共字符串金额{get;set;}
公共字符串Hail{get;set;}
公共列表区域详细信息{get;set;}
}
公共类区域详细信息
{
公共字符串DistBbsID{get;set;}
公共字符串子列表计数{get;set;}
公共字符串金额{get;set;}
公共字符串Hail{get;set;}
公共列表详细信息{get;set;}
}
公共类详细信息
{
公共字符串substbbsid{get;set;}
公共字符串金额{get;set;}
公共字符串Hail{get;set;}
公共字符串日期{get;set;}
}
将此模型类设置为您的模型类,以将
getRainsion()
的返回类型设置为此模型类

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

WebApiConfig.cs
中,或在使API请求通过标头中的
Application/json
时。

Hi;请用适当的格式将您的问题和帖子代码、数据和错误编辑为文本。@Stefan在我看来,他需要一个新类来容纳他的查询结果,在他的DB示例中,他似乎有3个过程正在执行并作为数据集返回,.pretty print的可能副本:所以您希望它返回经过修饰的Json?在WebApiConfig中使用Formatting=Formatting.Indented serializer设置注册JsonMediaTypeFormatter。请参阅此链接。控制器类如何?@sydur.rahman21我已经用控制器的示例实现更新了这个答案,用于处理将列表封装为json属性值的问题。
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});
            }
        }

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