2016-09-17 138 views
0

首先,我的道歉是因爲這將是一個「如何」的問題,而不是技術問題。我有一個CSV文件如下 -從C中的CSV文件創建JSON

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

現在我的計劃是在下面的格式 -

[ 
    { 
    "From": "London", 
    "To": "Dubai", 
    "Duration": 4 

    }, 
{ 
    "From": "Dubai", 
    "To": "Mumbai", 
    "Duration": 8 

    }, 
{ 
    "From": "Dubai", 
    "To": "Dhaka", 
    "Duration": 4 

    }, 
] 

我怎麼去和做創建從CSV JSON對象?目前我可以使用OpenFileDialog加載CSV,但不知道我應該怎麼做才能完成它?使用模型類? JSON.Net?請建議我和一些代碼示例,將不勝感激!

+0

http://stackoverflow.com/questions/10824165/converting-a-csv- file-to-json-using-c-sharp – Khurshid

回答

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

對於簡單的csv文件,使用類似[CSVHelper](https://github.com/joshclose/csvhelper)的解決方案可以爲您節省大量時間世界數據 –

+1

謝謝Oluwafemi – envyM6

0

您可以使用TextFieldParserMicrosoft.VisualBasic.FileIO命名空間和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(); 
    } 
} 

現在你可以使用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之前評估該查詢。

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

     } 

    }