通过从 csv 获取数据在 C# 中创建 json 数组

Posted

技术标签:

【中文标题】通过从 csv 获取数据在 C# 中创建 json 数组【英文标题】:Creating json array in C# by fetching data from csv 【发布时间】:2021-06-05 06:32:41 【问题描述】:

我想使用 C# 创建以下 json。所有数据都是从 csv 文件中提取的。


    "car":[
        
            "manufacturer": "Nissan",
            "fuelType": "petrol",
            "mileage": 20
        ,
        
            "manufacturer": "Nissan",
            "fuelType": "diesel",
            "mileage": 20

        ,
        
            "manufacturer": "Tesla",
            "fuelType": "electric",
            "mileage": 240
        ,
        
            "manufacturer": "Honda",
            "fuelType": "hybrid",
            "mileage": 100
        
    ]

以下是我编写的 C# 代码以及运行代码时得到的输出。我希望汽车是一个对象数组,而不是我得到一个包含单个汽车数组的汽车对象数组。我是 C# 和 json 的新手。

namespace createJSONfromCSV

    class Program
    
        static void Main(string[] args)
        
            string Path = @"C:\Files\CarDetails.csv";
            List<string> csvData = new List<string>();
            List<carDetails> carlist = new List<carDetails>();

            StreamReader reader = null;

            if (File.Exists(Path))
            
                reader = new StreamReader(File.OpenRead(Path));
                while (!reader.EndOfStream)
                
                    string line = reader.ReadLine();
                    csvData.Add(line);
                

                foreach(var item in csvData)
                
                    if(item != csvData[0])
                    
                        string[] fields = item.Split(',');
                        carlist.Add(new carDetails()
                        
                            cars = new List<car>()
                            
                                new car()
                                
                                    manufacturer = fields[0],
                                    fuelType = fields[1],
                                    mileage = Convert.ToInt32(fields[2])
                                
                            
                        );
                    
                
                var carDetailsjson = JsonConvert.SerializeObject(carlist, Formatting.Indented);
                Console.WriteLine(carDetailsjson);
            
            else
            
                Console.WriteLine("File does not exist...");
            
        
    



class carDetails
    
        public List<car> cars  get; set; 
    

    class car
    
        public string manufacturer get; set;
        public string fuelType  get; set; 
        public int mileage  get; set; 
    

我得到的输出如下:

[
    
      "cars": [
        
          "manufacturer": "Nissan",
          "fuelType": "Petrol",
          "mileage": 20
        
      ]
    ,
    
      "cars": [
        
          "manufacturer": "Nissan",
          "fuelType": "Diesel",
          "mileage": 60
        
      ]
    ,
    
      "cars": [
        
          "manufacturer": "Tesla",
          "fuelType": "Electric",
          "mileage": 240
        
      ]
    ,
    
      "cars": [
        
          "manufacturer": "Honda",
          "fuelType": "Hybrid",
          "mileage": 100
        
      ]
    
  ]

【问题讨论】:

列出一份汽车清单。不是每一行的列表。 【参考方案1】:

您应该在 foreach 条件下将 Car 对象添加到列表中,而不是仅具有 List 属性的 carDetails 对象。所以你的代码应该是这样的;

            List<car> carlist = new List<car>();
  carlist.Add(new car()
                                                         
                                    manufacturer = fields[0],
                                    fuelType = fields[1],
                                    mileage = Convert.ToInt32(fields[2])
                                );

【讨论】:

【参考方案2】:

只需建立一个汽车列表。在 foreach 中,您只需将汽车对象添加到列表中:

var cars = new List<car>();

foreach(var item in csvData)

     if(item != csvData[0])
     
           string[] fields = item.Split(',');

           cars.Add(new car()
           
                manufacturer = fields[0],
                fuelType = fields[1],
                mileage = Convert.ToInt32(fields[2])
           );
     


var carDetailsjson = JsonConvert.SerializeObject(new carDetails()  cars = cars , Formatting.Indented);

【讨论】:

以上是关于通过从 csv 获取数据在 C# 中创建 json 数组的主要内容,如果未能解决你的问题,请参考以下文章

通过从数据库中获取信息来显示已经选中的复选框

如何通过从 c# 对象中删除空值属性和零 (0) 值属性来优化 json

如何在 C# 中创建嵌套(父子)JSON 响应?

我想通过从 json 获取经度和纬度在谷歌地图上显示标记

PySpark 通过从十进制列中删除比例来写入 csv

Pandas:通过从列表的字典映射创建一列