-1

before you blame me, yes I did search for this topic/problem before I posted this question.

My Task is to Convert a CSV into a JSON with C# & Newtonsoft. However im having huge trouble with this Newtonsoft Documentation and dont understand sh*t..

My Idea was to:

  1. Give the Program the Path to the CSV.
  2. Read the CSV with a foreach loop.
  3. Add all the lines to a JSON Object.
  4. Save the JSON File in the same Folder.

This is the Code I got so far:

using System;
using System.IO;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace CSVtoJson
{
    class Program
    {
        static void Main(string[] args)
        {
            ConvertCsvFileToJsonObject();
            string ConvertCsvFileToJsonObject()
            {
                string path = "C:\\Dev\\CSVtoJSON\\csvtojson.csv";
                var csv = new List<string[]>();
                var lines = File.ReadAllLines(path);

                foreach (string line in lines)
                    csv.Add(line.Split(','));

                var properties = lines[0].Split(',');

                var listObjResult = new List<Dictionary<string, string>>();

                for (int i = 1; i < lines.Length; i++)
                {
                    var objResult = new Dictionary<string, string>();
                    for (int j = 0; j < properties.Length; j++)
                        objResult.Add(properties[j], csv[i][j]);

                    listObjResult.Add(objResult);
                }

                return JsonConvert.SerializeObject(listObjResult);
            }
        }
    }
}

However my Function does not seem to do anything, neither do I know how to create a JSON File and save it.. Im very thankful for every comment I'll get since im stuck on this for hours!! :)

tryinghard45
  • 21
  • 1
  • 5

1 Answers1

1

Your code for reading csv looks like it could work. Just use the information from Pavel Anikhouski's comments Try to change the line below and add a line after it.

from:

ConvertCsvFileToJsonObject();

into:

var jsonString = ConvertCsvFileToJsonObject();
File.WriteAllText(""C:\\Dev\\CSVtoJSON\\output.json"", jsonString);
mortb
  • 9,361
  • 3
  • 26
  • 44