我想将CSV文件记录(每个记录)转换为JSON文件。我已经试过了这段代码, 但这使我可以将文件完全转换为JSON,而不是为每条记录单独创建文件。
string[] cols;
string[] rows;
int cnt;
long unixSeconds = DateTimeOffset.Now.ToUnixTimeSeconds();
string desti = destination + unixSeconds.ToString();
StreamReader sr = new StreamReader(sourceFile); //SOURCEFILE
StreamWriter sw = new StreamWriter(desti); //DESTINATIONFILE
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];
cnt = i;
}
table.Rows.Add(dr);
string json = JsonConvert.SerializeObject(table, Formatting.Indented);
sw.Write(json);
}
sw.Close();
sr.Close();
实际输出
[ {
"Temprature": "30"
}]
[
{"Temprature": "30" }]
预期仅输出一条记录
[ { "Temprature": "30"
}
]
答案 0 :(得分:0)
sw
将json写入同一文件。您需要为每个记录指定不同的目标文件名。 2。如果您尝试使用destination+DateTimeOffset.Now.ToUnixTimeSeconds()
来提供不同的文件名,那么它会给出相同的名称(该过程非常快速,并且在毫秒内完成),并且仅显示最后一条记录(甚至没有追加记录)记录)。您需要使用Guid.NewGuid()
创建其他名称或其他任何技术。
string[] cols;
string[] rows;
int cnt;
StreamReader sr = new StreamReader(sourceFile); //SOURCEFILE
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];
cnt = i;
}
table.Rows.Add(dr);
string desti = destination + Guid.NewGuid(); //Destination file
StreamWriter sw = new StreamWriter(desti);
string json = JsonConvert.SerializeObject(table, Formatting.Indented);
sw.Write(json);
sw.Close();
}
sr.Close();