简体   繁体   中英

Serialize a csv to json with header record using json.net newtonsoft

I have a simple csv that I am trying to serialize to json. How do I include the header record as the name in the name value pairs?

  JsonSerializer serializer = new JsonSerializer();

  var csv = new List<string[]>();
  var lines = System.IO.File.ReadAllLines(file);
  foreach (string line in lines)
    csv.Add(line.Split(','));

  string json = JsonConvert.SerializeObject(csv, Formatting.Indented);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM