Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C中从CSV文件创建JSON#_C#_Json_Csv_Json.net - Fatal编程技术网

C# 在C中从CSV文件创建JSON#

C# 在C中从CSV文件创建JSON#,c#,json,csv,json.net,C#,Json,Csv,Json.net,首先,我道歉,因为这将是一个“如何”的问题,而不是一个技术问题。我有一个CSV文件,如下所示- London,Dubai,4 Dubai,Mumbai,8 Dubai,Dhaka,4 现在,我的计划是以以下格式从CSV创建一个JSON对象- [ { "From": "London", "To": "Dubai", "Duration": 4 }, { "From": "Dubai", "To": "Mumbai", "Duration"

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

您可以将csv记录添加到
列表中
,然后使用序列化来获取所需的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; }
    }
类程序
{
静态void Main(字符串[]参数)
{
string[]csv=new[]{“伦敦,迪拜,4”,“迪拜,孟买,8”,“迪拜,达卡,4”};
列表=新列表();
foreach(csv中的var项目)
{
string[]字段=item.Split(',');
列表。添加(新模型)
{
From=字段[0],
To=字段[1],
持续时间=字段[2]
});
}
var json=JsonConvert.SerializeObject(列表);
Console.WriteLine(json);
Console.ReadLine();
}
}
公共类模型
{
来自{get;set;}的公共字符串
{get;set;}的公共字符串
公共字符串持续时间{get;set;}
}
您可以从命名空间和
Microsoft.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();
    }
}
在这里,我使用的是相同的代码,但也可以用于


请确保在关闭
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();
            }

        }

    }
公共类程序
{
公共静态void Main(字符串[]args)
{
var list=新列表();
WriteLine(“放入.csv文件的路径”);
var response1=Console.ReadLine();
Console.WriteLine(“初始化…”);
//读取.csv文件中的所有行
var csvFile=File.ReadAllLines(response1);
//获取第一行,并将其命名为字段名
var fieldNamesArray=csvFile.First().Split(',');
//获取.csv中的列数
//执行-1,以便可以将其用于下面的索引器
var fieldNamesIndex=fieldNamesArray.Count()-1;
//跳过第一行,创建一个不带字段名的IEnumerable
var csvValues=csvFile.Skip(1);
//遍历所有记录
foreach(CSV值中的var项目)
{
var newDiction=newdictionary();
对于(int i=0;i
对于简单的csv文件,您的答案是正确的,使用类似的工具可以在您使用真实数据时节省大量时间
            json = JsonConvert.SerializeObject(query, Formatting.Indented);
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();
            }

        }

    }