【问题标题】:C# CSV to JSON with Newtonsoft使用 Newtonsoft 将 C# CSV 转换为 JSON
【发布时间】:2020-10-27 10:31:53
【问题描述】:

在你责怪我之前,是的,我在发布这个问题之前确实搜索过这个主题/问题。

我的任务是使用 C# 和 Newtonsoft 将 CSV 转换为 JSON。 但是我在使用这个 Newtonsoft 文档时遇到了很大的麻烦,而且我不明白 sh*t..

我的想法是:

  1. 为程序提供 CSV 的路径。
  2. 使用 foreach 循环读取 CSV。
  3. 将所有行添加到 JSON 对象。
  4. 将 JSON 文件保存在同一文件夹中。

这是我目前得到的代码:

using System;
using System.IO;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace CSVtoJson
{
    class Program
    {
        static void Main(string[] args)
        {
            ConvertCsvFileToJsonObject();
            string ConvertCsvFileToJsonObject()
            {
                string path = "C:\\Dev\\CSVtoJSON\\csvtojson.csv";
                var csv = new List<string[]>();
                var lines = File.ReadAllLines(path);

                foreach (string line in lines)
                    csv.Add(line.Split(','));

                var properties = lines[0].Split(',');

                var listObjResult = new List<Dictionary<string, string>>();

                for (int i = 1; i < lines.Length; i++)
                {
                    var objResult = new Dictionary<string, string>();
                    for (int j = 0; j < properties.Length; j++)
                        objResult.Add(properties[j], csv[i][j]);

                    listObjResult.Add(objResult);
                }

                return JsonConvert.SerializeObject(listObjResult);
            }
        }
    }
}

但是我的函数似乎没有做任何事情,我也不知道如何创建 JSON 文件并保存它。我非常感谢我收到的每条评论,因为我坚持了几个小时! :)

【问题讨论】:

标签: c# json serialization json.net


【解决方案1】:

您用于读取 csv 的代码看起来可以正常工作。 只需使用来自 Pavel Anikhouski 的 cmets 的信息 尝试更改下面的行并在其后添加一行。

来自:

ConvertCsvFileToJsonObject();

进入:

var jsonString = ConvertCsvFileToJsonObject();
File.WriteAllText(""C:\\Dev\\CSVtoJSON\\output.json"", jsonString);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-23
    • 2012-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    相关资源
    最近更新 更多