把json file 转成Dictionary

本文介绍了一个名为JsonFileParser的类,用于从JSON流中解析数据并转换为IDictionary<string, string>,支持对象、数组和基本类型。关键方法包括Parse和内部的VisitElement、VisitValue等处理不同JSON值的函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

定义一个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}");
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值