把json file 转成Dictionary

定义一个JsonFileParser

 public class JsonFileParser
    {
        private JsonFileParser() { }
        public static IDictionary<string, string> Parse(Stream input)
        {
            return new JsonFileParser().ParseStream(input);
        }
        private IDictionary<string, string> ParseStream(Stream input)
        {
            this._data.Clear();
            JsonDocumentOptions options = new JsonDocumentOptions
            {
                AllowTrailingCommas = false,
                CommentHandling = JsonCommentHandling.Skip
            };
            using (var streamReader = new StreamReader(input))
            {
                using (var jsonDocument = JsonDocument.Parse(streamReader.ReadToEnd(), options))
                {
                    if (jsonDocument.RootElement.ValueKind != JsonValueKind.Object)
                    {
                        throw new FormatException("Error_UnsupportedJSONToken");
                    }
                    VisitElement(jsonDocument.RootElement);
                }
            }
            return _data;
        }

        private void VisitElement(JsonElement element)
        {
            foreach (JsonProperty jsonProperty in element.EnumerateObject())
            {
                this.EnterContext(jsonProperty.Name);
                this.VisitValue(jsonProperty.Value);
                this.ExitContext();
            }
        }
        private void VisitValue(JsonElement value)
        {
            switch (value.ValueKind)
            {
                case JsonValueKind.Object:
                    VisitElement(value);
                    return;
                case JsonValueKind.Array:
                    {
                        int num = 0;
                        using(JsonElement.ArrayEnumerator enumerator=value.EnumerateArray().GetEnumerator())
                        {
                            while (enumerator.MoveNext())
                            {
                                JsonElement value2 = enumerator.Current;
                                this.EnterContext(num.ToString());
                                this.VisitValue(value2);
                                this.ExitContext();
                                num++;
                            }
                            return;
                        }
                        break;
                    }
                case JsonValueKind.String:
                case JsonValueKind.Number:
                case JsonValueKind.True:
                case JsonValueKind.False:
                case JsonValueKind.Null:
                    break;
                default:
                    throw new FormatException("Error_UnsupportedJSONToken");
            }
            string currentPath = this._currentPath;
            if (this._data.ContainsKey(currentPath))
            {
                throw new FormatException("Error_UnsupportedJSONToken");
            }
            this._data[currentPath] = value.ToString();
        }
        private void EnterContext(string context)
        {
            this._context.Push(context);
            this._currentPath = ConfigurationPath.Combine(this._context.Reverse<string>());
        }
        private void ExitContext()
        {
            this._context.Pop();
            this._currentPath = ConfigurationPath.Combine(this._context.Reverse<string>());
        }
        private readonly IDictionary<string, string> _data = new SortedDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        private readonly Stack<string> _context = new Stack<string>();
        private string _currentPath;

    }

直接调用Parse方法即可

FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);

    var dic = JsonFileParser.Parse(fileStream);
    foreach (KeyValuePair<string, string> keyValuePair in dic)
    {
        Console.WriteLine($"{keyValuePair.Key}:{keyValuePair.Value}");
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在 .NET 中,可以使用第三方库来将 Excel 文件转换为 JSON 格式。 一种方法是使用 EPPlus 库,该库提供了用于读取和写入 Excel 文件的功能。要使用 EPPlus 库,首先需要安装它。可以使用 NuGet 管理器在 Visual Studio 中安装 EPPlus 库,或者在命令提示符中使用以下命令进行安装: ``` dotnet add package EPPlus ``` 然后,可以使用以下代码将 Excel 文件转换为 JSON 格式: ```csharp using OfficeOpenXml; using Newtonsoft.Json; // 加载 Excel 文件 using (var package = new ExcelPackage(new FileInfo("filename.xlsx"))) { // 获取第一个工作表 var worksheet = package.Workbook.Worksheets[1]; // 读取工作表的数据 var data = worksheet.Cells .Select(cell => cell.Value) .ToArray(); // 将数据转换为 JSON string json = JsonConvert.SerializeObject(data); } ``` 这段代码会将 Excel 文件中的数据读取到内存中,然后使用 Newtonsoft.Json 库将数据转换为 JSON 格式。 另一种方法是使用 ExcelDataReader 库,该库提供了用于读取 Excel 文件的功能。要使用 ExcelDataReader 库,首先需要安装它。可以使用 NuGet 管理器在 Visual Studio 中安装 ExcelDataReader 库,或者在命令提示符中使用以下命令进行安装: ``` dotnet add package ExcelDataReader ``` 然后,可以使用以下代码将 Excel 文件转换为 JSON 格式: ```csharp using ExcelDataReader; ### 回答2: 将Excel转换为JSON是一个常见的需求,可以利用.NET提供的一些库和功能来实现。 首先,我们需要使用.NET中的Interop库来加载和操作Excel文件。可以使用Microsoft.Office.Interop.Excel命名空间中的相关类来处理Excel文件。通过创建一个Excel应用程序对象和一个工作簿对象,我们可以打开并读取Excel文件的内容。 读取Excel文件后,可以使用.NET中的一些内置的数据操作类来提取数据并将其转换为JSON格式。循环遍历每个工作表和单元格,将数据存储在适当的结构中,然后使用.NET中的JavaScriptSerializer类将其转换为JSON字符串。 以下是实现将Excel转换为JSON的大致步骤: 1. 引用Interop库: ``` using Microsoft.Office.Interop.Excel; ``` 2. 创建并打开Excel应用程序: ``` Application excelApp = new Application(); Workbook excelWorkbook = excelApp.Workbooks.Open("excel文件路径"); ``` 3. 选择要处理的工作表: ``` Worksheet excelWorksheet = excelWorkbook.Sheets["工作表名称"]; ``` 4. 读取并提取数据: ``` List<Dictionary<string, object>> jsonData = new List<Dictionary<string, object>>(); Range excelRange = excelWorksheet.UsedRange; int rowCount = excelRange.Rows.Count; int colCount = excelRange.Columns.Count; for (int row = 1; row <= rowCount; row++) { Dictionary<string, object> rowData = new Dictionary<string, object>(); for (int col = 1; col <= colCount; col++) { string cellValue = Convert.ToString(((Range)excelWorksheet.Cells[row, col]).Value2); string columnName = Convert.ToString(((Range)excelWorksheet.Cells[1, col]).Value2); rowData.Add(columnName, cellValue); } jsonData.Add(rowData); } ``` 5. 转换为JSON字符串: ``` JavaScriptSerializer serializer = new JavaScriptSerializer(); string json = serializer.Serialize(jsonData); ``` 最后,我们可以使用.NET中的其他方法(如File.WriteAllText方法)将转换后的JSON字符串保存到文件或进行其他操作。 需要注意的是,转换Excel文件的性能和可靠性可能会受到Excel版本和文件大小的影响。因此,在实际应用中,可能需要进行一些优化和错误处理的操作。 ### 回答3: 在使用.NET将Excel转成JSON的过程中,我们可以借助一些开源库和.NET的内置功能来实现。 首先,我们需要使用EPPlus库来读取Excel文件中的数据。EPPlus库是一个用于操作Excel文件的强大工具,可以帮助我们读取、写入和修改Excel文件。我们可以使用EPPlus提供的方法,例如LoadFromCollection(),来将Excel文件的内容加载到一个DataTable中。 接下来,我们需要将DataTable中的数据转换成JSON格式。我们可以使用Json.NET库来实现这一功能。Json.NET是一个功能强大的JSON处理库,可以帮助我们在.NET应用程序中序列化和反序列化JSON数据。我们可以使用JsonConvert.SerializeObject()方法将DataTable对象转换成JSON字符串。 最后,我们可以将JSON字符串写入到一个JSON文件中。我们可以使用.NET的内置功能,例如File.WriteAllText()方法,将JSON字符串写入到一个指定的文件中。 综上所述,使用.NET将Excel转换成JSON的步骤可以概括为:使用EPPlus库读取Excel文件中的数据到DataTable,使用Json.NET库将DataTable转换成JSON字符串,然后使用.NET的内置功能将JSON字符串写入到一个JSON文件中。这样我们就可以在.NET环境下方便地将Excel文件转换成JSON格式了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值