Here is the basic nature of what i’m doing. Note: this is pseudocode.. this code is from memory, and I don’t have intellisense to bark at me about syntax! 🙂
(Description after the code)
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());
}
}
I’m developing an AJAX calendar app. As you can see, I”m getting a list of workshops and appointments, which have a lot in common (property-wise). There are actually 20+ properties in the EventView class. Thus, I’ve made a ViewModel that holds the properties I need serialized, many of which are common to both appointments and workshops. This is really helpful on the JS side of things, as my app is agnostic about whether each event is an appointment or workshop.
While Appointments and Workshops have a lot in common, they don’t use the exact same set of properties in EventView (notice Appointment just uses prop1 and prop2, while Appointment uses prop1, prop2, prop3 and prop5).
Currently, I’m sending back 200KB of JSON as a result of this request. Sadly, probably 25% of this is fluff from the properties that are serialized but not used — sending back an workshop serialized as {prop1='value', prop2='value', prop3='', prop4='', prop5=''}.
So here’s the question: When I return Json(data) in the controller, is there a way to iterate through all the serialized data and remove all properties that have no value? Essentially I’d like to write a method that accomplishes this: json(data).RemoveEmptyProperties();
Thoughts?
Using the travers library (https://github.com/substack/js-traverse), something like this will remove all empty nodes: