为了账号安全,请及时绑定邮箱和手机立即绑定

在 .net core MVC 中创建 JSON

在 .net core MVC 中创建 JSON

C#
慕田峪7331174 2022-01-15 16:42:35
我是 .net 核心编程的新手。我在如何格式化我的 Json 对象时遇到问题。我想创建一个 Json 对象,并且该 JSON 的字段之一将处理一个 Json 对象。我正在使用 MVC 架构。谢谢这是我的代码。    public async Task<List<Schedule>> getAllScheds(){        dynamic response = new JObject();        try {            var data = await _context.MlfbSchedules                        .Include(h => h.Team1)                        .Include(a => a.Team2)                        .Include(s => s.StadiumID)                        .ToListAsync();            return data;        } catch (Exception e) {            response.Error = e.ToString();            return response;        }    }此函数正在返回此数据。 [     {         "scheduleId": 43,         "team1": {             "teamId": 1,             "city": "Virginia",             "teamName": "Armada",             "sImage": "/images/teams-logo-small/virginia.png",             "image": "/images/teams-logo/virginia.png",             "helmetImage": "/images/teams-helmet/virginia.png",             "createdBy": null,             "createdDate": "2016-06-22T10:03:35.58",             "modifiedBy": null,             "modifiedDate": null,             "isDeleted": null         },         "team2": {             "teamId": 3,             "city": "Florida",             "teamName": "Fusion",             "sImage": "/images/teams-logo-small/florida.png",             "image": "/images/teams-logo/florida.png",             "helmetImage": "/images/teams-helmet/florida.png",             "createdBy": null,             "createdDate": "2016-06-22T10:03:35.58",             "modifiedBy": null,             "modifiedDate": null,             "isDeleted": null         },
查看完整描述

1 回答

?
慕丝7291255

TA贡献1859条经验 获得超6个赞

为了格式化响应,您可以实现自己的 Dto,如下所示:


    public class ResultDto<T> where T : class

{

    public ResultDto(string status, IList<T> data)

    {

        Status = status;

        Data = data;

    }

    public string Status { get; set; }

    public IList<T> Data { get; set; }

}

然后改变你的方法


        public async Task<ResultDto<Product>> getAllScheds()

    {

        dynamic response = new JObject();

        try

        {


            var data = new List<Product>

                     {

                         new Product{ProductId=Guid.NewGuid().ToString(),Name="142525"},

                         new Product{ProductId=Guid.NewGuid().ToString(),Name="122555"},

                         new Product{ProductId=Guid.NewGuid().ToString(),Name="125255"}

                     };

            return new ResultDto<Product>("success", data);

        }

        catch (Exception e)

        {

            response.Error = e.ToString();

            return response;

        }


    }


查看完整回答
反对 回复 2022-01-15
  • 1 回答
  • 0 关注
  • 330 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号