MVC控制器中的嵌套Json数组
本文关键字:Json 数组 嵌套 控制器 MVC | 更新日期: 2023-09-27 18:17:10
这个问题很傻。但我想不明白。
在c# MVC控制器动作中,我需要为测试目的建模一个Json数组。
但是这显示了编译错误,而不是有效的Json:
var result = {
"controllerId": "controller1",
"controllerName": "ControllerOne"
};
但是这是完全有效的:
var scheduleResult = new[]
{
new { scheduleId = "schedule1",scheduleName = "scheduleOne"},
new { scheduleId = "schedule2",scheduleName = "scheduleTwo"}
};
还有如何编写嵌套Json数组:
I tried:
var scheduleResult = new[]
{
new { scheduleId = "schedule1",scheduleName = "scheduleOne",new[]{ new {doorId="Door1",doorName="DoorOne"}, new { doorId = "Door2", doorName = "DoorTwo" } } },
new { scheduleId = "schedule2",scheduleName = "scheduleTwo"}
};
但是显示语法错误。
我需要在该数组的每个元素中嵌套数组。
提前感谢。
c#不支持你的写作方式。你不能只在c#中输入JSON就指望它能正常工作。你可以尝试使用匿名类型:
var result = new
{
controllerId = "controller1",
controllerName = "ControllerOne",
myArray = new []
{
"a",
"b"
}
};
如果您将其作为API调用的结果返回,则将其转换为JSON,没有问题。
你正在谈论的嵌套数组不工作,因为你需要给他们一个名字,你不能有数组属性没有名字。
为什么不使用Dictionary<TKey, TValue>
和Newtonsoft.Json
呢?
简单的json:
IDictionary<string, string> obj = new Dictionary<string, string>();
obj.Add("controllerId", "controller1");
obj.Add("controllerName", "ControllerOne");
// {"controllerId":"controller1","controllerName":"ControllerOne"}
string json = JsonConvert.SerializeObject(obj);
嵌套json: IList<string> obj = new List<string>();
IDictionary<string, string> first = new Dictionary<string, string>();
first.Add("scheduleId ", "schedule1");
first.Add("scheduleName", "scheduleOne");
IDictionary<string, string> second = new Dictionary<string, string>();
second.Add("scheduleId ", "schedule2");
second.Add("scheduleName", "scheduleTwo");
string first_json = JsonConvert.SerializeObject(first);
string second_json = JsonConvert.SerializeObject(second);
obj.Add(first_json);
obj.Add(second_json);
// ["{'"scheduleId '":'"schedule1'",'"scheduleName'":'"scheduleOne'"}","{'"scheduleId '":'"schedule2'",'"scheduleName'":'"scheduleTwo'"}"]
string json = JsonConvert.SerializeObject(obj);
首先,我们应该使用与返回类型相同的模式创建模型类
public class ScheduleModel
{
public List<Schedule> ScheduleList { get; set; }
}
public class Schedule
{
public int ScheduleId { get; set; }
public string ScheduleName { get; set; }
public List<Door> DoorList { get; set; }
}
public class Door
{
public int DoorId { get; set; }
public string DoorName { get; set; }
}
现在在控制器Action中创建测试数据
List<Door> doorList = new List<Door>();
doorList.Add(new Door{DoorId = "Door1",DoorName = "DoorOne"});
doorList.Add(new Door{DoorId = "Door2",DoorName = "DoorTwo"});
List<Schedule> scheduleList = new List<Schedule>();
scheduleList.Add(new Schedule{
ScheduleId = "schedule1",
ScheduleName = "scheduleOne",
DoorList = doorList
});
scheduleList.Add(new Schedule
{
ScheduleId = "schedule2",
ScheduleName = "scheduleTwo",
});
return Json(scheduleList, JsonRequestBehavior.AllowGet);
如果这个答案对你有益,请标记为答案。