Skip to main content
 首页 » 编程设计

c#之ASP.NET MVC。创建模型以转换为 JSON 对象(具有动态名称属性)

2024年02月05日17haluo1

我需要像这样生成 Json 输出:

{ 
    "01:30":{ 
        "FREE":true, 
        "PRICE":3500 
     }, 
    "03:00":{ 
        "FREE":true, 
        "PRICE":2500 
    }, 
    "13:30":{ 
        "FREE":true, 
        "PRICE":2500 
    } 
} 

我的问题是时间字符串——它是从一个条目到另一个条目的动态。我不知道如何构建将被序列化为正确的 json 结果的 c# 类(模型)。 我的模型现在看起来像这样:

public class ScheduleViewModel 
{ 
    public ScheduleInnerViewModel TIME { get; set; } 
} 
 
public class ScheduleInnerViewModel 
{ 
    public bool FREE { get; set; } 
    public int PRICE { get; set; } 
} 

输出结果是(错误的):

[ 
    {"TIME":{ 
        "FREE":true, 
        "PRICE":3500 
     }}, 
    {"TIME":{ 
        "FREE":true, 
        "PRICE":2500 
    }}, 
    {"TIME":{ 
        "FREE":true, 
        "PRICE":2500 
    }} 
] 

我使用标准方式从 Controller 生成 json 结果:

List<ScheduleViewModel> model = new List<ScheduleViewModel>(); 
//fill the model... 
return this.Json(model, JsonRequestBehavior.AllowGet); 

请您参考如下方法:

如果有一个字典,其中的键是一个字符串(您的时间戳)并且数据是您的模型类呢?

喜欢:

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); 

输出: