Converting a csv file to json using C#

后端 未结 14 1700
余生分开走
余生分开走 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:50

    If you can use System.Web.Extensions, something like this could work:

    var csv = new List(); // or, List
    var lines = System.IO.File.ReadAllLines(@"C:\file.txt");
    foreach (string line in lines)
        csv.Add(line.Split(',')); // or, populate YourClass          
    string json = new 
        System.Web.Script.Serialization.JavaScriptSerializer().Serialize(csv);
    

    You might have more complex parsing requirements for the csv file and you might have a class that encapsulates the data from one line, but the point is that you can serialize to JSON with one line of code once you have a Collection of lines.

提交回复
热议问题