【问题标题】:CSV to Nested JSON C#CSV 到嵌套 JSON C#
【发布时间】:2020-07-06 09:31:26
【问题描述】:

我想将一个 csv 文件转换为带有嵌套对象和嵌套数组的 json。示例 csv 如下所示。我的 csv 结构可以是动态的,但我可以将其保持为静态以获得下面所需的格式。我知道有很多类似问题的答案,但没有一个能解决我的嵌套对象的具体问题。

Id,name,nestedobject/id,nestedarray/0/name
1,name,2,namelist
2,name1,3,namelist1

我想要下面的 json,特别是第 3 列和第 4 列(嵌套对象)有问题

[{"Id": 1,
"name": "name",
"nestedobject": {
"id": 2
},
"nestedarray": [{
"name": "namelist"
}
]
},
{"Id": 2,
"name": "name1",
"nestedobject": {
"id": 3
},
"nestedarray": [
{"name": "namelist1"}]
}
]

请注意,为了保持 csv 文件结构动态,我在列名中传递数据类型 - 例如,“System.Int32:Id”将是我的第一列,而不是“Id”。如何修改我的代码以考虑嵌套对象?

public static DataTable ReadCsvFile(string fileName)
        {
            DataTable oDataTable = new DataTable();
            StreamReader oStreamReader = new StreamReader(fileName);
            bool hasColumns = false;

            List<string> ColumnNames = new List<string>();

            string[] oStreamDataValues = null;

            while (!oStreamReader.EndOfStream)
            {
                String oStreamRowData = oStreamReader.ReadLine();
                if(oStreamRowData.Length > 0)
                {
                    oStreamDataValues = oStreamRowData.Split(',');
                    if(!hasColumns)
                    {
                        int i = 0;
                        foreach(string csvcolumn in oStreamRowData.Split(','))
                        {
                            string[] nameWithType = csvcolumn.Split(':');
                            DataColumn oDataColumn = new DataColumn(nameWithType[1], typeof(string));
                            ColumnNames.Add(nameWithType[1]);
                            var type = System.Type.GetType(nameWithType[0]);

                            oDataColumn.DataType = type;
                            oDataTable.Columns.Add(oDataColumn);
                            i = i + 1;
                        }
                        hasColumns = true;
                    }
                    else
                    {
                        DataRow oDataRow = oDataTable.NewRow();
                        for(int i = 0; i < ColumnNames.Count; i++)
                        {

                         oDataRow[ColumnNames[i]] = oStreamDataValues[i] == null ? string.Empty : oStreamDataValues[i].ToString();

                        }
                        oDataTable.Rows.Add(oDataRow);
                    }
                }
            }
            oStreamReader.Close();
            oStreamReader.Dispose();


            return oDataTable;
        }

我最后把DataTable序列化了

DataTable dt = ReadCsvFile(filePath);
                dt.CaseSensitive = true;
                var jsonData = JsonConvert.SerializeObject(dt); 

【问题讨论】:

  • joshclose.github.io/CsvHelper 是您想要使用的。不要重新发明轮子。
  • @Matt - 我的问题是如何存储嵌套对象以获取提到的 JSON 格式
  • 您首先必须将该列解析为文本,然后是 foreach 条目,根据需要构建对象,然后序列化为 JSON。

标签: c# json csv nested


【解决方案1】:

使用Cinchoo ETL这个开源库,你可以这样做

string csv = @"Id,name,nestedobject/id,nestedarray/0/name, nestedarray/0/city, nestedarray/1/name, nestedarray/200/city
1,name,2,namelist10, citylist10,namelist11, citylist11
2,name1,3,namelist20, citylist20,namelist21, citylist21";

StringBuilder json = new StringBuilder();
using (var w = new ChoJSONWriter(json))
{
    using (var r = ChoCSVReader.LoadText(csv).WithFirstLineHeader()
        .Configure(c => c.NestedColumnSeparator = '/')
        )
        w.Write(r);
}
Console.WriteLine(json.ToString());

输出

[
 {
  "Id": 1,
  "name": "name",
  "nestedobject": {
    "id": 2
  },
  "nestedarray": [
   {
     "name": "namelist10",
     "city": "citylist10"
   },
   {
     "name": "namelist11"
   }
  ]
 },
 {
  "Id": 2,
  "name": "name1",
  "nestedobject": {
    "id": 3
  },
  "nestedarray": [
   {
     "name": "namelist20",
     "city": "citylist20"
   },
   {
     "name": "namelist21"
   }
  ]
 }
]

【讨论】:

  • 谢谢。你摇滚!
  • 如果我想要一个使用 Cinchoo ETL 的字符串列表,你能告诉我应该如何格式化 csv 吗?例如我的 JSON 看起来像 {id: 1, name: Tom, friends: [Dick, Harry]}。源 csv 应该是什么样子?
  • 请在 SO 中打开一个新问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-14
  • 2021-07-26
  • 2022-01-15
  • 2016-06-28
  • 2016-05-16
相关资源
最近更新 更多