c# - 将 CSV(嵌套对象)转换为 JSON

标签 c# json csv choetl

我需要在 JSON 对象中转换 CSV 数据(包含一行标题和一行数据)。 CSV 包含嵌套列,有一个例子:

id,name,category/id,category/name,category/subcategory/id,category/subcategory/name,description
0,Test123,15,Cat123,10,SubCat123,Desc123

我希望 JSON 看起来像这样:

{
    "id": 0,
    "name": "Test123",
    "category": {
        "id": 15,
        "name": "Cat123",
        "subcategory": {
            "id": 10,
            "name": "SubCat123",
        }
    },
    "description": "Desc123"
}

我尝试了 CsvHelper 和 ChoETL 库,但没有成功,因为据我所知,这些库要求我有一个类作为模型,但我没有这些类,因为数据是完全动态的。

本站http://www.convertcsv.com/csv-to-json.htm是成功做到这一点的一个很好的例子。 只需粘贴我在上面创建的 JSON,转到第 3 步并选中“重新创建嵌套对象和数组”选项,然后在第 5 步中单击“CSV 到 JSON”。

但我需要在不使用外部框架的情况下在我的应用程序中实现这一点。

我怎样才能让它发挥作用?

最佳答案

如果没有,添加newtonsoft library(dll),然后添加以下引用

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

添加以下类

   public class Rootobject
        {
            public int id { get; set; }
            public string name { get; set; }
            public Category category { get; set; }
            public string description { get; set; }
        }

        public class Category
        {
            public int id { get; set; }
            public string name { get; set; }
            public Subcategory subcategory { get; set; }
        }

        public class Subcategory
        {
            public int id { get; set; }
            public string name { get; set; }
        }

然后使用此代码

 DataTable CSVData = new DataTable(); // your csv rows



            HashSet<Rootobject> MyObjectsList = new HashSet<Rootobject>(); //create hashset to handle your classes
            foreach(DataRow row in CSVData.Rows)
            {
                //change the indices in ItemArray with the right indices
                MyObjectsList.Add(new Rootobject() {
                    id = (int)row.ItemArray[0], name = (string)row.ItemArray[0], category = new Category() {
                        id = (int)row.ItemArray[0], name = (string)row.ItemArray[0], subcategory = new Subcategory() {
                            id = (int)row.ItemArray[0], name = (string)row.ItemArray[0]
                        }
                    }
                });


            }





            string _ResultObj = JsonConvert.SerializeObject(MyObjectsList);  //here get your json string

关于c# - 将 CSV(嵌套对象)转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46654451/

相关文章:

c# - 带有 XML 文件的 Entity Framework

无法使用数字键作为字符串的 PHP 数组

c# - 拥有信用卡模型安全吗?

python - 使用 Python 将 CSV 转换为 JSON(特定格式)

c# - JSON数据html参数

PHP:解析包含很长行的文本文件的有效方法是什么?

Python导入CSV排序代码( Pandas ?)在条目中用 ';'和 ','分隔

xml - Bash 将 XML 解析为逗号分隔列表

c# - 如何使用 JSON.NET 序列化并忽略可空结构值

c# - 如何在 Settings.Default 上保存 List<string>?