-1

This is my code

The CSV file is incredibly simple (i thought i start off simple - 2 rows):

Name,Address Dave,example street 1 Charlie,example street 2 jordan,Example 3 Ross,simple Street

I am trying to print out the CSV data into JSON. I know i am missing a few things but I'm just not sure what. Any help would be great

The plan is to add functionality to change the data to XML, but for now i just need it to change CSV data into JSON.

noobi3
  • 40
  • 8

1 Answers1

2

You need to change var csv = new List<string[]>(); to var csv = new List<PeopleDataClass>();.

Do not convert in foreach everytime. In foreach just parse line and push top list.

Then you will have PeopleDataClass list. You can convert to json now.

var csv = new List<PeopleDataClass>();
var lines = File.ReadAllLines(@"C:\Users\kordiseps\Desktop\New Text Document.txt");
foreach (var line in lines)
{
    csv.Add(new PeopleDataClass
    {
        Address = line.Split(',')[0],
        Name = line.Split(',')[1]
    });
}
string json = JsonConvert.SerializeObject(csv);
kordiseps
  • 391
  • 3
  • 12
  • Thanks for that, how do i actually return the newly serialized JSON data? When I run that, nothing happens because i haven't returned anything yet. https://i.gyazo.com/39dc2ef19b2e4c1678afa6aaff9f07e6.png – noobi3 Feb 21 '21 at 13:40
  • Add `Console.WriteLine(json);` below `string json = JsonConvert.SerializeObject(csv);` – kordiseps Feb 21 '21 at 18:34
  • What do you want to with this json? Save to file? – kordiseps Feb 21 '21 at 18:34