【发布时间】:2011-08-15 13:42:29
【问题描述】:
这是我正在做的事情的基本性质。注意:这是伪代码..这段代码来自内存,我没有智能感知来向我咆哮语法! :-)
(代码后的说明)
Controller:
{
public JSONResult GetCalendar(Form){
var data = Workshops.Select().ToEventViews();
var moreData = Appointments.Select().ToEventViews();
data.AddRange(moreData);
return Json(data);
}
}
ViewModel
{
public class EventView{
string prop1;
string prop2;
string prop3;
string prop4;
string prop5;
}
}
BLL
{
public EventView ToEventView(Workshop w){
return new EventView{
prop1 = w.thing;
prop2 = w.thing2;
//props 3, 4 and 5 not needed
}
}
public EventView ToEventView(Appointment a){
return new EventView{
prop1 = a.thing;
prop2 = a.thing;
prop3 = a.thing;
prop5 = a.thing;
}
}
public List<EventView> ToEventView(List<Workshop> wshops){
return wshops.ConvertAll(w=> w.ToEventView().ToList());
}
public List<EventView> ToEventView(List<Appointment> appts){
return appts.ConvertAll(a=> a.ToEventView().ToList());
}
}
我正在开发一个 AJAX 日历应用程序。正如你所看到的,我得到了一个研讨会和约会列表,它们有很多共同点(属性方面)。EventView 类中实际上有 20 多个属性。因此,我制作了一个 ViewModel包含我需要序列化的属性,其中许多对约会和研讨会都很常见。这在 JS 方面非常有用,因为我的应用程序不知道每个事件是约会还是研讨会。
虽然 Appointments 和 Workshops 有很多共同点,但它们在 EventView 中并没有使用完全相同的一组属性(注意 Appointment 只使用 prop1 和 prop2,而 Appointment 使用 prop1、prop2、prop3 和 prop5)。
目前,由于此请求,我发回了 200KB 的 JSON。可悲的是,其中 25% 可能是来自已序列化但未使用的属性的绒毛——发回序列化为 {prop1='value', prop2='value', prop3='', prop4='', prop5=''} 的研讨会。
那么问题来了:当我在控制器中return Json(data) 时,有没有办法遍历所有序列化数据并删除所有没有价值的属性?本质上我想写一个方法来完成这个:json(data).RemoveEmptyProperties();
想法?
【问题讨论】:
标签: c# asp.net-mvc json