-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.

2
  • Code is text, could you add your code to the question? Commented Feb 21, 2021 at 12:44
  • Move the serialize code outside the foreach loop. In short you need to serialize csv Commented Feb 21, 2021 at 12:48

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

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. i.gyazo.com/39dc2ef19b2e4c1678afa6aaff9f07e6.png
Add Console.WriteLine(json); below string json = JsonConvert.SerializeObject(csv);
What do you want to with this json? Save to file?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.