envyM6 envyM6 - 2 months ago 15
JSON Question

Creating JSON from a CSV file in C

First of all my apologies because this is going to be a "How to" question rather than a technical question. I have a CSV file as follows-

London,Dubai,4
Dubai,Mumbai,8
Dubai,Dhaka,4


Now my plan is to create a JSON object from that CSV in the following format-

[
{
"From": "London",
"To": "Dubai",
"Duration": 4

},
{
"From": "Dubai",
"To": "Mumbai",
"Duration": 8

},
{
"From": "Dubai",
"To": "Dhaka",
"Duration": 4

},
]


How do I go about and do that? Currently I can load the CSV using
OpenFileDialog
but no idea what else I should do to get it done? Use Model Classes? JSON.Net? Please advice me and some code samples would be appreciated!

Answer

You can add csv records to a List<T> and then serialize it with Newtonsoft.Json to get your required JSON object. See the example below:

    class Program
    {
        static void Main(string[] args)
        {
            string[] csv = new[] { "London,Dubai,4", "Dubai,Mumbai,8", "Dubai,Dhaka,4" };
            List<model> list = new List<model>();

            foreach (var item in csv)
            {

                string[] fields = item.Split(',');
                list.Add(new model
                {
                    From = fields[0],
                    To = fields[1],
                    Duration = fields[2]
                });
            }

            var json = JsonConvert.SerializeObject(list);
            Console.WriteLine(json);
            Console.ReadLine();

        }
    }

    public class model
    {
        public string From { get; set; }
        public string To { get; set; }
        public string Duration { get; set; }
    }
Comments