在C中从CSV文件创建JSON

时间:2016-09-17 18:53:13

标签: c# json csv

首先,我道歉,因为这将是一个“如何”问题,而不是技术问题。我有一个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?请给我建议,一些代码示例将不胜感激!

3 个答案:

答案 0 :(得分:2)

您可以将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; }
    }

答案 1 :(得分:0)

您可以使用TextFieldParser命名空间中的Microsoft.VisualBasic.FileIOMicrosoft.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 = JsonConvert.SerializeObject(query, Formatting.Indented);

请务必在关闭TextFieldParser之前评估查询。

答案 2 :(得分:0)

我相信这应适用于所有不同类型的.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();
            }

        }

    }