【问题标题】:How to return complex Json object in asp.net mvc如何在asp.net mvc中返回复杂的Json对象
【发布时间】:2016-12-29 17:47:03
【问题描述】:

我正在使用实体框架从数据库中获取数据并将其序列化为 JSON。我希望我的 JSON 响应如下所示。 我应该在我的模型中添加items 属性并制作我想要的 JSON 吗?谢谢。

所需的 Json

{
      "items" : [
        {
          "Id": 1,
          "AdContent":"Content1"
        },
        {
          "Id": 2,
          "AdContent":"Content2"
        },
        {
          "Id": 3,
          "AdContent":"Content3"
        }   
      ]
}

我收到的当前 JSON

[
    {
        "Id":1,
        "AdContent":"Content1"
    },
    {
         "Id":2,
         "AdContent":"Content2"
    },
    { 
         "Id":3,
         "AdContent":"Content3"
    }
]

{

控制器

public JsonResult GetJson()
{
     using (var db = new DoskaUsContext())
     {
         List<AdViewModel> list = db.Ads.Select(x => new AdViewModel
         {
             Id = x.AdId,                    
             AdContent = x.AdContent
         }).ToList();

         return Json(list, JsonRequestBehavior.AllowGet);
     }
}

型号

 public class AdViewModel
    {
        public int Id { get; set; }
        public string AdContent { get; set; }        
    }

【问题讨论】:

  • return Json(new { items = list }, JsonRequestBehavior.AllowGet);

标签: c# asp.net json asp.net-mvc asp.net-mvc-4


【解决方案1】:

匿名对象是一种解决方案Json(new {items=list},...)

解决该问题的一般方法 - 使用 http://json2csharp.com/ 生成强类型类,并通过生成的类填充结果,或者至少查看代码中缺少的内容。

在这种特殊情况下生成的代码:

public class Item
{
    public int Id { get; set; }
    public string AdContent { get; set; }
}

public class RootObject
{
    public List<Item> items { get; set; }
}

其中显示了缺失的部分 - RootObject 和列表属性 items

【讨论】:

    【解决方案2】:

    创建另一个模型,其中包含 AdViewModel 的集合作为项目

     public class AdViewModel
        {
            public int Id { get; set; }
            public string AdContent { get; set; }        
        }
    
     public class NewModel
        {
            public AdViewModel items { get; set; }
        }
    

    【讨论】:

    • 好的,我按照你说的创建,但是接下来呢?我有同样的问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 2019-12-12
    相关资源
    最近更新 更多