[英]How to return complex Json object in asp.net mvc
I am using entity framework to get data from database and serialize it to JSON. 我正在使用实体框架从数据库获取数据并将其序列化为JSON。 And I want my JSON response looks like the one below. 我希望我的JSON响应如下所示。 Shoud I add items
property to my model and make JSON I want? 我应该将items
属性添加到我的模型中并创建JSON吗? Thanks. 谢谢。
Desired Json 期望的杰森
{
"items" : [
{
"Id": 1,
"AdContent":"Content1"
},
{
"Id": 2,
"AdContent":"Content2"
},
{
"Id": 3,
"AdContent":"Content3"
}
]
}
Current JSON I receive 我收到的当前JSON
[
{
"Id":1,
"AdContent":"Content1"
},
{
"Id":2,
"AdContent":"Content2"
},
{
"Id":3,
"AdContent":"Content3"
}
]
{
Controller 控制者
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);
}
}
Model 模型
public class AdViewModel
{
public int Id { get; set; }
public string AdContent { get; set; }
}
Anonymous object is one solution Json(new {items=list},...)
. 匿名对象是Json(new {items=list},...)
一种解决方案。
General approach to solve that problem - generate strongly typed classes with http://json2csharp.com/ and populate result via generated classes or at least see what is missing from your code. 解决该问题的一般方法-使用http://json2csharp.com/生成强类型的类,并通过生成的类填充结果,或者至少查看代码中缺少的内容。
In this particular case generated code: 在这种特殊情况下生成的代码:
public class Item
{
public int Id { get; set; }
public string AdContent { get; set; }
}
public class RootObject
{
public List<Item> items { get; set; }
}
Which shows missing piece of the puzzle - RootObject
with list property items
. 其中显示了缺少的拼图-具有列表属性items
RootObject
。
Create another model which hold collection of AdViewModel
as items 创建另一个将AdViewModel
集合作为项目保存的模型
public class AdViewModel
{
public int Id { get; set; }
public string AdContent { get; set; }
}
public class NewModel
{
public AdViewModel items { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.