【发布时间】:2020-11-09 18:12:23
【问题描述】:
我正在使用 c# 将 csv 文件转换为 json 文件,但我收到的文件只是一堆值。我想在转换为 json 时将它们保存为 key => value 格式。
我的代码:
static void ReadFromCsv()
{
var csv = new List<string[]>();
var lines = System.IO.File.ReadAllLines(@"C:\path\details.csv");
foreach (string line in lines)
csv.Add(line.Split(','));
var json = JsonSerializer.Serialize(csv);
File.WriteAllText(@"C:\path2\jsontest.json", json);
}
json 文件是这样结束的:
[
"20-7-2020",
"Ben",
"Smith",
"+27745004488",
"Orange",
"Tree",
"54 Victoria Road"
],
[
"20-7-2020",
"Jade",
"Hodsin",
"+27743456060",
"Apple",
"Plant",
"20 Small Street"
]
我的目标是让 json 看起来像下面这样,以便于存储到 sql DB 中:
[
"Date" : "20-7-2020",
"Name" : "Ben",
"Surname" : "Smith",
"Cell" : "+27745004488",
"Food" : "Orange",
"Source" : "Tree",
"Address" : "54 Victoria Road"
],
[
"Date" : "20-7-2020",
"Name" : "Jade",
"Surname" : "Hodsin",
"Cell" : "+27743456060",
"Food" : "Apple",
"Source" : "Plant",
"Address" : "20 Small Street"
]
【问题讨论】:
-
您可能希望
csv成为List<object>并相应地填充它。不过考虑使用现有的 CSV 库。无需重新发明轮子。 -
问题是客户端没有用密钥发送它,我将如何填充 'List
-
您是说 CSV 不包含标题行吗?你能从其他地方得到这些信息吗?是否会发生变化?
-
是的,没有标题行。我必须手动添加标题。它可能会改变,但现在让我们假装它不会改变。
-
有一个固定的标题让它更简单,看我的回答...