CSV到嵌套JSON C# [英] CSV to Nested JSON C#

查看:74
本文介绍了CSV到嵌套JSON C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to convert a csv file into json with nested objects and nested array. The sample csv looks like below. My csv structure can be dynamic, but I am ok to keep it static to get the required format below. I know there are so many answers to similar questions, but none addressing my specific issue of nested objects.

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

我想要如下所示的json,尤其是在第3列& 4(嵌套对象)

I want the json like below, specifically having trouble with column 3 & 4 (nested objects)

[{"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".如何修改代码以说明嵌套对象?

Please note to keep the csv file structure dynamic I pass the datatype in the column name - for e.g.. "System.Int32:Id" will be my first column instead of "Id". How can I modify my code to account for the nested objects?

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

I serialize the DataTable in the end

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

推荐答案

使用 Cinchoo ETL ,这是一个开放源代码库,您可以按以下步骤进行操作

With Cinchoo ETL, an open source library, you can do it as follows

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"
   }
  ]
 }
]

这篇关于CSV到嵌套JSON C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆