Converting a csv file to json using C#

后端 未结 14 1695
余生分开走
余生分开走 2020-12-04 22:10

I was wondering if someone\'s written a utility to convert a CSV file to Json using C#. From a previous question on stackoverflow, I\'m aware of this nice utility - https://

14条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 22:55

    I looked for the answer for this question finally i solved it by using Dictionary

    public static void CreateJsonFromCSV()
    {
        string path = "C:\\Users\\xx\\xx\\xx\\xx\\lang.csv";
        string textFilePath = path;
        const Int32 BufferSize = 128;
    
        using (var fileStream = File.OpenRead(textFilePath))
        using (var streamReader = new StreamReader(fileStream, Encoding.UTF8, true, BufferSize))
        {
            String line;
            Dictionary jsonRow = new Dictionary();
    
            while ((line = streamReader.ReadLine()) != null)
            {
    
                string[] parts = line.Split(',');
    
                string key_ = parts[0];
                string value = parts[1];
    
    
                if (!jsonRow.Keys.Contains(key_))
                {
                    jsonRow.Add(key_, value );
                }
    
            }
            var json = new JavaScriptSerializer().Serialize(jsonRow);
            string path_ = "C:\\XX\\XX\\XX\\XX\\XX.csv";
            File.WriteAllText(path_, json);
        }
    
    } 
    

提交回复
热议问题