You can use a List of Dictionary<string,string>
but you also need to get the header row from the csv. I have a rough idea for you below.
// initialize the list
var list = new List<Dictionary<string, string>>();
var lines = System.IO.File.ReadAllLines("");
// get your header values
var headers = lines[0].Split(',');
// Here you want to skip the first line because it is the header
foreach (string line in lines.Skip(1))
{
// split your line to get individual values
var lineSplit = line.Split(',');
// make a dictionary to hold the line values
var dictionary = new Dictionary<string, string>();
// do a for loop to apply your headers
for (int i = 0; i < headers.Length; i++)
{
dictionary.Add(headers[i], lineSplit[i]);
}
// Add your dictionary to the list
list.Add(dictionary);
}
string json = JsonConvert.SerializeObject(list, Formatting.Indented);
The above will give you an array that is not wrapped in an object. If you would like something that will wrap it into an object you can just make a simple class to take care of that. Example below.
public class CsvToJson
{
public CsvToJson()
{
this.List = new List<Dictionary<string, string>>();
}
public CsvToJson(string filePath)
{
this.List = new List<Dictionary<string, string>>();
// Adding some exception prevention
if (File.Exists(filePath))
{
ConvertFromCsvToJson(filePath);
}
}
public List<Dictionary<string, string>> List { get; set; }
private void ConvertFromCsvToJson(string filePath)
{
var lines = File.ReadAllLines(filePath);
// get your header values
var headers = lines[0].Split(',');
foreach (string line in lines.Skip(1))
{
// split your line to get individual values
var lineSplit = line.Split(',');
// make a dictionary to hold the line values
var dictionary = new Dictionary<string, string>();
// do a for loop to apply your headers
for (int i = 0; i < headers.Length; i++)
{
dictionary.Add(headers[i], lineSplit[i]);
}
// Add your dictionary to the list
List.Add(dictionary);
}
}
}
Then you could easily call on this anytime by using something like below.
var rootObject = new CsvToJson("C:\testFile.csv");
var json = JsonConvert.SerializeObject(rootObject, Formatting.Indented);
>` and use the header line items to set the key and then read in the value from each line?