用c#从CSV文件创建JSON

本文关键字:文件创建 JSON CSV | 更新日期: 2023-09-27 18:07:18

首先,我很抱歉,因为这将是一个"如何"的问题,而不是一个技术问题。我有一个CSV文件如下-

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

现在我的计划是从该CSV创建一个JSON对象,格式如下-

[
  {
    "From": "London",
    "To": "Dubai",
    "Duration": 4
  },
{
    "From": "Dubai",
    "To": "Mumbai",
    "Duration": 8
  },
{
    "From": "Dubai",
    "To": "Dhaka",
    "Duration": 4
  },
]

我该怎么做呢?目前我可以使用OpenFileDialog加载CSV,但不知道我还应该做些什么来完成它?使用模型类?JSON.Net ?请建议我和一些代码样本将不胜感激!

用c#从CSV文件创建JSON

您可以将csv记录添加到List<T>中,然后使用Newtonsoft对其进行序列化。Json来获取所需的Json对象。请看下面的例子:

    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; }
    }

可以使用Microsoft.VisualBasic.FileIO命名空间中的TextFieldParserMicrosoft.VisualBasic.dll程序集来解析CSV文件。尽管这个类的名字是VisualBasic,但它在c#中是完全可用的。

首先,添加以下扩展方法:
public static class TextFieldParserExtensions
{
    public static IEnumerable<string []> ReadAllFields(this TextFieldParser parser)
    {
        if (parser == null)
            throw new ArgumentNullException();
        while (!parser.EndOfData)
            yield return parser.ReadFields();
    }
}

现在可以使用LINQ将每个CSV行转换为匿名或命名类型以进行序列化,如下所示:

        var csv = @"London,Dubai,4
Dubai,Mumbai,8
Dubai,Dhaka,4";
        string json;
        using (var stream = new StringReader(csv))
        using (TextFieldParser parser = new TextFieldParser(stream))
        {
            parser.SetDelimiters(new string[] { "," });
            var query = parser.ReadAllFields()
                .Select(a => new { From = a[0], To = a[1], Duration = int.Parse(a[2]) });
            json = new JavaScriptSerializer().Serialize(query);
        }

这里我使用JavaScriptSerializer,但相同的代码可以与json.net使用

            json = JsonConvert.SerializeObject(query, Formatting.Indented);

确保在关闭TextFieldParser之前评估查询

我相信这应该适用于所有不同类型的。csv文件

注释在代码

public class Program
    {
        public static void Main(string[] args)
        {
            var list = new List<Dictionary<string, string>>();
            Console.WriteLine("Put in the path to your .csv file");
            var response1 = Console.ReadLine();
            Console.WriteLine("Initializing...");
            // Read All of the lines in the .csv file
            var csvFile = File.ReadAllLines(response1);

            // Get The First Row and Make Those You Field Names
            var fieldNamesArray = csvFile.First().Split(',');
            // Get The Amount Of Columns In The .csv
            // Do the -1 so you can use it for the indexer below
            var fieldNamesIndex = fieldNamesArray.Count() - 1;
            // Skip The First Row And Create An IEnumerable Without The Field Names
            var csvValues = csvFile.Skip(1);
            // Iterate Through All Of The Records
            foreach (var item in csvValues)
            {
                var newDiction = new Dictionary<string, string>();
                for (int i = 0; i < fieldNamesIndex;)
                {
                    foreach (var field in item.Split(','))
                    {
                        // Think Of It Like This
                        // Each Record Is Technically A List Of Dictionary<string, string>
                        // Because When You Split(',') you have a string[]
                        // Then you iterate through that string[]
                        // So there is your value but now you need the field name to show up
                        // That is where the Index will come into play demonstrated below
                        // The Index starting at 0 is why I did the -1 on the fieldNamesIndex variable above
                        // Because technically if you count the fields below its actually 6 elements
                        //
                        // 0,1,2,3,4,5 These Are The Field Names
                        // 0,1,2,3,4,5 These Are The Values
                        // 0,1,2,3,4,5
                        //
                        // So what this is doing is int i is starting at 0 for each record
                        // As long as i is less than fieldNamesIndex
                        // Then split the record so you have all of the values
                        // i is used to find the fieldName in the fieldNamesArray
                        // Add that to the Dictionary
                        // Then i is incremented by 1
                        // Add that Dictionary to the list once all of the values have been added to the dictionary
                        //

                        // Add the field name at the specified index and the field value
                        newDiction.Add(fieldNamesArray.ElementAt(i++), field);
                    }
                    list.Add(newDiction);
                }
            }

            Console.WriteLine("Would You Like To Convert To Json Now?");
            Console.WriteLine("[y] or [n]");
            var response = Console.ReadLine();
            if (response == "y")
            {
                Console.WriteLine("Where Do You Want The New File?");
                var response2 = Console.ReadLine();
                // Serialize the list into your Json
                var json = JsonConvert.SerializeObject(list);
                File.Create(response2).Dispose();
                File.AppendAllText(response2, json);
                Console.WriteLine(json);
                Console.ReadLine();
            }
            else
            {
                Console.WriteLine("Ok See You Later");
                Console.ReadLine();
            }
        }
    }