views:

57

answers:

2

In C# i have an array of Calendar objects

each Calendar object has an array of CalendarEvent objects

each CalendarEvent object has a Date and Name property

i want to convert this to Json object but i want to change the data structure a bit so in the json object a calendar is an array of dates and an array of names (breakdown the CalendarEvent object)

i want something like this:

var myObject = return Json(new
                {
                    Calendars = new[]
                    {
                         Dates = new [] {myDateArray};
                         Names = new [] {myNameArray};
                    }
                }
A: 

For .Net 3.5, you'd be looking for the DataContractJsonSerializer. You'll probably want to customise it to match what you want.

cofiem
Oh no, why reinvent the wheel? Are you suggesting to manually use a serializer when the `Json` method already does this?
Darin Dimitrov
Oh, I didn't realise .Net had a `Json` object/method. Msdn ref?
cofiem
+3  A: 
IEnumerable<Calendar> calendars = ...

return Json(
    calendars.Select(calendar => new
    {
        Names = calendar.CalendarEvents.Select(e => e.Name),
        Dates = calendar.CalendarEvents.Select(e => e.Date)
    })
);
Darin Dimitrov