[英]ASP.NET MVC. Create model to convert into JSON-object (with dynamic name property)
I need to generate Json-output like this: 我需要生成这样的Json输出:
{
"01:30":{
"FREE":true,
"PRICE":3500
},
"03:00":{
"FREE":true,
"PRICE":2500
},
"13:30":{
"FREE":true,
"PRICE":2500
}
}
My problem here is time string - its dynamic from one entry to another. 我的问题是时间字符串-它从一个条目到另一个条目的动态变化。 I can not figure out how to construct my c# class (model) that will be serialized into proper json result.
我不知道如何构造将序列化为正确的json结果的c#类(模型)。 My model looks like this now:
我的模型现在看起来像这样:
public class ScheduleViewModel
{
public ScheduleInnerViewModel TIME { get; set; }
}
public class ScheduleInnerViewModel
{
public bool FREE { get; set; }
public int PRICE { get; set; }
}
Output result is (wrong): 输出结果是(错误):
[
{"TIME":{
"FREE":true,
"PRICE":3500
}},
{"TIME":{
"FREE":true,
"PRICE":2500
}},
{"TIME":{
"FREE":true,
"PRICE":2500
}}
]
I use standard way to generate json result from controller: 我使用标准方法从控制器生成json结果:
List<ScheduleViewModel> model = new List<ScheduleViewModel>();
//fill the model...
return this.Json(model, JsonRequestBehavior.AllowGet);
Try the unaccepted answer from this post . 尝试此帖子中不可接受的答案。 It uses a Dictionary to create the property name (key) and then you can use your ScheduleInnerViewModel as the value so something like:
它使用Dictionary创建属性名称(键),然后可以使用ScheduleInnerViewModel作为值,如下所示:
var obj = new Dictionary<string, ScheduleInnerViewModel>();
What about having a dictionary where the key is a string (your timestamp) and the data is your model class ? 如果有一个字典,键是一个字符串(您的时间戳),而数据是您的模型类,该怎么办?
Like: 喜欢:
Dictionary<string, ScheduleInnerViewModel> dic = new Dictionary<string, ScheduleInnerViewModel>();
dic.Add("01:30", new ScheduleInnerViewModel{ Free = false, Price = 100 });
dic.Add("04:25", new ScheduleInnerViewModel{ Free = false, Price = 200 });
dic.Add("13:00", new ScheduleInnerViewModel{ Free = true, Price = 0 });
var json = JsonConvert.SerializeObject(dic, new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented });
Console.WriteLine(json);
Output: 输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.