【问题标题】:How to return JSON Array in ASP.NET Web API C#如何在 ASP.NET Web API C# 中返回 JSON 数组
【发布时间】:2018-06-01 18:18:17
【问题描述】:

我想以以下格式返回(在网络浏览器中显示)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# 和 Entity Framework 5.0 中使用 asp.net Web API (MVC),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;
            }
        }

    }
}

我的输出就像我不想要的那样。

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

还有

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

我的 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();
        }
    }
}

谁能帮帮我???

【问题讨论】:

  • 您好;请编辑您的问题并将代码、数据和错误发布为具有适当格式的文本。
  • @Stefan 在我看来,他需要一个新类来存放他的查询结果,在他的数据库示例中,看起来他有 3 个 procs 正在执行并作为数据集返回。
  • 漂亮打印的可能副本:stackoverflow.com/questions/9847564/…
  • 所以你希望它返回你的 Json 美化?使用 WebApiConfig 中的 Formatting = Formatting.Indented SerializerSetting 注册您的 JsonMediaTypeFormatter。

标签: c# arrays json asp.net-web-api


【解决方案1】:

如果您想默认返回美化 JSON,您需要在 WebApiConfig 中配置媒体类型格式化程序。

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

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

您还可以在此处设置其他默认选项,例如将属性序列化为 camelCase (CamelCasePropertyNamesContractResolver),或排除空属性的输出 (NullValueHandling.Ignore)。

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

  • 将控制器操作的返回类型更改为 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});
            }
        }

    }
}

【讨论】:

  • @sydur.rahman21 我已经用控制器的示例实现更新了这个答案,用于处理将列表封装为 json 属性的值。
【解决方案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; }
}

将此作为您的模型类,以将GetRainFall() 的返回类型设置为此模型类。

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

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

【讨论】:

  • 控制器类怎么样?
猜你喜欢
  • 2016-12-20
  • 1970-01-01
  • 2014-05-01
  • 2017-05-05
  • 1970-01-01
  • 2012-09-19
  • 1970-01-01
  • 1970-01-01
  • 2013-09-21
相关资源
最近更新 更多