我试图将 CSV 数据转换为 JSON。它安静地工作得很好,但很少有列有逗号,在转换为 json 时,逗号包含的数据被拆分。这是我试过的代码,
var path = @"C:xyz\\abc.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);
}
var json = JsonConvert.SerializeObject(listObjResult, Formatting.Indented);
List<ABCModel> desrilize = JsonConvert.DeserializeObject<List<ABCModel>>(json);
return desrilize;
CSV 数据
employee,emp city,state,emp address
"abc","efg","lkj","building name"
"wer","sdf","qwe","afj Building, near cross"
在上面的第三行中包含逗号,在转换为 json 时不应拆分。在使用上面的代码时,它会被拆分。请帮忙。
在“emp city”中也有一个空间,如何在创建模型时为其定义jsonProperty。
预期的 json
[
{
"employee": "abc",
"emp city": "efg",
"state": "lkj",
"emp address": "building name"
},
{
"employee": "wer",
"emp city": "sdf",
"state": "qwe",
"emp address": "afj Building, near cross"
}
]
先感谢您。