c# - How to convert list to json in c#
问题描述
I have converted CSV to a list of string I want to create a JSON using the header of CSV file the input and output are as mentioned below
var list = [
[a,b,c],
[1,2,3],
[4,5,6]
];
to
var json = {
{
"a":1,
"b":2,
"c":3
},
{
"a":4,
"b":5,
"c":6
}
}
解决方案
Assuming your list looks like
var list = new string[3][] {
new string[3] { "a","b","c" },
new string[3] {"1","2","3" },
new string[3] {"4","5","6"}
};
You can make a json from it using this method:
public static string toJson(string[][] csvArray) {
var sb = new StringBuilder("{\n\"elements\": [\n");
var headers = new string[csvArray[0].Length];
for(int i = 0; i < csvArray[0].Length; i++)
{
headers[i] = csvArray[0][i];
}
for(int i = 1; i < csvArray.Length; i++)
{
sb.AppendLine("{");
for(int j = 0; j < csvArray[i].Length; j++)
{
sb.AppendLine("\"" + headers.ElementAtOrDefault(j) + "\": \"" + csvArray[i][j] + "\",");
}
sb.Remove(sb.Length-3, 3); // remove last ",/n" to make json valid
sb.AppendLine("\n},");
}
sb.Remove(sb.Length-3, 3); // remove last ",/n" to make json valid
sb.AppendLine("\n]\n}");
return sb.ToString();
}
Check it in fiddler. Some alterations might be needed to adjust to your input data, maybe some additional validations, but it will let you go forward.
推荐阅读
- r - 如何将 summary() 的结果显示为绘图/grob?
- azure - 将 az storage 命令与 azurite 一起使用
- ruby-on-rails - Pundit 使用非直接关联模型授权索引操作
- android - 警报管理器设置为同一时间 onReceive 仅调用一次
- java - 无法将名称 [org.hibernate.dialect.MYSQL5Dialect] 解析为策略 [org.hibernate.dialect.Dialect]
- php - 查询不考虑传入参数的日期范围
- angular - 使用 Angular 材料按列过滤谓词表
- kubernetes - 将日志从 kubernetes 转发到 splunk
- eclipse - 使用`make`创建Eclipse项目?
- c# - Protobuf-Net NotSupportedException:类型不能表示为封闭不可变类型的默认值(UnityEngine.Vector3)