Search code examples
c#jsonlistumbracostrong-typing

Add object to list in Umbraco controller


I am rather new in strongly typed languages and I working on a Umbraco controller that outputs some JSON with a list of dates.

"meetingTimes": [10:30, 11:30]

That works pretty well. Now I want to output an extry field with the time containing a unique key

So it should be like

meetingTimes: [{ time: "10:30", key: "abcd-1234-efgh-5678" }, { time: "11:30", key: "defg-1234-sktg-5678" }]

But I can't figure out how to do it.

The part of my current code that handles this is:

try {            
                IPublishedContent content = Umbraco.Content(Guid.Parse("ff3e93f6-b34f-4664-a08b-d2eae2a0adbd"));
                var meetingDatesAvailabled = content.Value<IEnumerable<IPublishedElement>>("meetingDatesAvailable");
            
                var items = new List<object>();
               
                foreach(var meetingDate in meetingDatesAvailabled)
                {
                    if (meetingDate.Value("meetingItemDay").ToString().Substring(0, 8) == theDate) {
                        var times = meetingDate.Value<IEnumerable<IPublishedElement>>("meetingItemDayTimes");

                        foreach (var time in times)
                        {
                            items.Add(time.Value("meetingdateTimeItem").ToString());
                        }
                    }
                }

                return new { dateChosen = theDate, meetingTimes = items };
            }

Solution

  • Initially, we have to create a class that abstract the meeting time:

    public class MeetingTime
    {
        public string Time { get; }
        public Guid   Key  { get; }
    
        public MeetingTime(string time, Guid key)
        {
            Time = time;
            Key = key;
        }
    } 
    

    Then we are going to create an empty list of MeetingItem, instead of creating an empty list of object, var items = new List<object>();.

    var items = new List<MeetingItem>();
    

    Then inside you foreach:

    foreach (var time in times)
    {
        items.Add(new MeetingTime(time.Value("meetingdateTimeItem").ToString(), 
                                  Guid.NewGuid())
        );
    }
    

    Note: I am not aware of the way you serialize your objects (e.g. https://www.newtonsoft.com), but quite probably you have to decorate both properties Time and Key with an attribute for using a proper name during the serialization. If you don't do so, then it would use the default names, Time and Key. I say this, because I noticed in the json you shared that you want to be time and key.