using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using System.Data;
using System.Text.RegularExpressions;
namespace jsonPractice
{
class Program
{
static void Main(string[] args)
{
string[] cols;
string[] rows;
StreamReader sr = new StreamReader(@"F:\Sample.csv"); //SOURCE FILE
StreamWriter sw = new StreamWriter(@"F:\sample.json"); // DESTINATION FILE
string line = sr.ReadLine();
cols = Regex.Split(line, ",");
DataTable table = new DataTable();
for (int i = 0; i < cols.Length; i++)
{
table.Columns.Add(cols[i], typeof(string));
}
while ((line = sr.ReadLine()) != null)
{
table.Rows.Clear();
int i;
string row = string.Empty;
rows = Regex.Split(line, ",");
DataRow dr = table.NewRow();
for (i = 0; i < rows.Length ; i++)
{
dr[i] = rows[i];
}
table.Rows.Add(dr);
string json = JsonConvert.SerializeObject(table, Formatting.Indented);
sw.Write(json);
}
sw.Close();
sr.Close();
}
}
}
Just so you know, you are writing out the entire table but with just a single row, over and over again. One would expect something like:
ReplyDelete[
{...},
{...},
]
but instead we get
[{...}],
[{...}],
The problem is on
ReplyDeletetable.Rows.Clear();
line. Remove it and all works fine