Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Serializing List<DayOfWeek> in C#

I’m trying to create a JSON array that contains list of weekdays.

I’m testing this in a console app but it keeps giving me an error i.e. exited with code 0.

Here’s what I’m doing:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

using Newtonsoft.Json;

var days = new List<DayOfWeek>();
days.Add(DayOfWeek.Monday);
days.Add(DayOfWeek.Wednesday);

var json = JsonConvert.SerializeObject(days);
Console.WriteLine(json);

What am I doing wrong?

>Solution :

First, use System.Text.Json, as it’s more up to date.

Second, you can do what you want with a Linq expression…

var days = JsonSerializer.Serialize(Enum.GetValues(typeof(DayOfWeek))
  .Cast<DayOfWeek>().ToList());

Not actually sure if you need the Cast<> in there, but this certainly works.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading